branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>PartMan7/PartBot<file_sep>/pmcommands/mports.js
module.exports = {
help: `Displays the available ports for a term.`,
permissions: 'coder',
commandFunction: function (Bot, by, args, client) {
if (!args.length) return Bot.pm(by, 'Uhh, what ports should I get?');
const sources = Object.values(data.pokedex).map(m => m.name);
const terms = args.join(' ').split(/,/), term = toID(terms.shift());
const out = tools.getPorts(term, sources);
let front = `<details><summary>Front</summary><hr/>`;
try {
let fc = terms.length ? terms.join(',') : 'true;';
if (!fc.includes('return ')) fc = 'return ' + fc;
const func = new Function(`return function (m, dex) {${fc}}`)();
front += out[0].filter(m => func(data.pokedex[toID(m)], data.pokedex)).join('<br/>') || 'None.';
} catch (e) {
Bot.log(e);
return Bot.pm(by, e.message);
}
front += '<hr/></details>';
let end = `<details><summary>End</summary><hr/>`;
try {
let fc = terms.length ? terms.join(',') : 'true;';
if (!fc.includes('return ')) fc = 'return ' + fc;
const func = new Function(`return function (m, dex) {${fc}}`)();
end += out[1].filter(m => func(data.pokedex[toID(m)], data.pokedex)).join('<br/>') || 'None.';
} catch (e) {
Bot.log(e);
return Bot.pm(by, e.message);
}
end += '<hr/></details>';
return Bot.sendHTML(by, front + '<br/>' + end);
}
};
<file_sep>/pmcommands/jbg.js
module.exports = {
help: `Board Games Galore!`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
Bot.pm(by, `/invite Board Games`);
}
};
<file_sep>/data/TABLE/board.js
exports.board = function (inputHeaders, input, sort, styling, widths, rank, limit) {
/*
headers: string[] - headers is an array of the array headers; ie, the title row
input: [[]] - input is a nested array of the input of the table
sort: function - sort is a single function that is run on each input element
styling: string[] - styling is the styilng applied to separate elements
widths: number[] - width is an array that takes the width of each column
rank: string - creates a new column at the beginning with the ranks
limit: number - Maximum entries to display.
*/
const headers = Array.from(inputHeaders);
if (!Array.isArray(headers) || !headers[0] || typeof headers[0] !== 'string') return 1;
if (!Array.isArray(input) || !input[0] || !Array.isArray(input[0])) return 2;
if (typeof sort !== 'function') return 3;
if (styling.length === 2) styling.push(styling[1]);
if (!Array.isArray(styling) || styling.length !== 3 || typeof styling[0] !== 'string') return 4;
const data = Array.from(input).filter(row => row.length === headers.length);
if (rank) headers.unshift(rank);
if (!widths || !Array.isArray(widths)) {
widths = Array.from({ length: headers.length }).fill(Math.floor(100 / headers.length) + '%');
}
let html = '<table style="border-collapse:collapse; border-spacing:0; border-color:#aaa;"><colgroup>';
for (let i = 0; i < headers.length; i++) html += `<col style="width:${widths[i]}">`;
html += '</colgroup>';
html += '<tr>';
for (let i = 0; i < headers.length; i++) html += `<th style="${styling[0]}">${headers[i]}</th>`;
html += '</tr>';
if (!data.length) return 5;
try {
data.sort((x, y) => {
return sort(y) - sort(x);
}).forEach((row, index) => {
if (rank) row.unshift(index + 1);
});
html += data.map((row, index) => {
if (limit && index >= limit) return;
let text = '<tr>';
if (index % 2 === 0) text += row.map(term => `<td style="${styling[1]}">${term}</td>`).join('');
else text += row.map(term => `<td style="${styling[2]}">${term}</td>`).join('');
text += '</tr>';
return text;
}).join('');
html += '</table>';
return html;
} catch (e) {
console.log(e);
return e.message;
}
};
<file_sep>/pmcommands/shop.js
module.exports = {
help: `Displays a room's Shop. Syntax: ${prefix}shop (room)`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
let room = tools.getRoom(args.join('').toLowerCase().replace(/[^a-z0-9-]/g, ''));
if (!room) {
const rooms = Bot.getRooms(by).filter(r => Bot.rooms[r] && Bot.rooms[r].shop);
if (rooms.length === 0) return Bot.pm(by, "You don't know any of my shops...");
if (rooms.length === 1) room = rooms[0];
// eslint-disable-next-line max-len
else return Bot.sendHTML(by, `Multiple room shops found! Which did you mean?<br>` + rooms.map(r => `<button name="send" value="/msg ${Bot.status.nickName},${prefix}shop ${r}">${Bot.rooms[r].title}</button>`));
}
if (!room || !Bot.rooms[room]) return Bot.pm(by, 'Invalid room.');
if (!Bot.rooms[room].shop) return Bot.pm(by, `${Bot.rooms[room].title} doesn't have a Shop...`);
if (!Bot.rooms[room].lb) return Bot.pm(by, "No points here.");
const shop = Bot.rooms[room].shop;
const lb = Bot.rooms[room].lb;
const user = lb.users[toID(by)] || { points: Array.from({ length: lb.points.length }).map(t => 0) };
// TODO: Holy shit rewrite this HTML
let out = `<div style="background: white; color: black;">
${shop.img && shop.img.src ? `<img src="${shop.img.src}" height="137" width="126" style="float: left; align: top">` : ''}
<center>
<br>
<br>
<b style="font-family: verdana;">Your Balance:</b>
<div style="font-family:courier;">
<br>
${lb.points.map((p, i) => `${p[1]}: ${user.points[i]}`).join('\n\t\t\t<br>\n\t\t\t')}
<br>
<br>
<br>
</div>
<details><summary><b style="font-family: verdana; font-size: 95%">Available Items:</b></summary>
<br>
<div style="font-family:courier;">`;
const data = shop.inventory;
// eslint-disable-next-line max-len
out += tools.board(Object.keys(data).map(id => [`<button name="send" value="/msg ${Bot.status.nickName},${prefix}buyitem ${room}, ${id}" style="background: none; border: none; font-family: courier; color: black; font-size: 100%">${data[id].name}</button>`, ...data[id].cost]), ['Name', ...lb.points.map(p => p[2])], (row) => -(row[1] + row[2] * 100000), ['180px', ...Array.from({ length: lb.points.length }).map(t => Math.ceil(120 / lb.points.length) + 'px')], 'shop', null);
out += `
</div>
</details>
<br>
</center>
</div>`;
return Bot.sendHTML(by, out);
}
};
<file_sep>/discord/me.js
module.exports = {
help: `Toggles the ME role.`,
guildOnly: "750048485721505852",
commandFunction: function (args, message, Bot) {
if (message.member.roles.cache.find(r => r.id === '750049070206419055')) {
message.member.roles.remove(message.guild.roles.cache.get("750049070206419055")).then(() => {
message.channel.send('The ME role has been removed.');
}).catch(Bot.log);
} else message.member.roles.add(message.guild.roles.cache.get("750049070206419055")).then(() => {
message.channel.send('The ME role has been added.');
}).catch(Bot.log);
}
};
<file_sep>/discord/addhints.js
const PZ = require('../data/PUZZLES/index.js');
module.exports = {
help: `Adds the specified number of hints to the specified team.`,
guildOnly: PZ.guildID,
commandFunction: function (args, message, Bot) {
if (!message.member.roles.cache.has(PZ.IDs.staff)) {
return message.channel.send('Access denied.').then(msg => msg.delete({ timeout: 3000 }));
}
if (!args.length) return message.channel.send("Which team?");
const cargs = args.join(' ').split(',');
if (!cargs[1]) return message.channel.send("How many? (negative numbers work)");
const team = PZ.getTeam(toID(cargs.shift())), amt = parseInt(cargs.join('').replace(/[^0-9-]/g, ''));
if (!team) return message.channel.send("Couldn't get the team you meant.");
if (typeof amt !== 'number') return message.channel.send("Invalid amount.");
if (!amt) return message.channel.send('> add 0 hints');
PZ.addHints(team, amt)
.then(nam => message.channel.send(`${amt} hint(s) added! ${team.name} now has ${nam} hint(s).`))
.catch(e => Bot.log(e));
}
};
<file_sep>/handlers/minorhandler.js
module.exports = {
initialize: () => {
Bot.DB = require('origindb')('data/DATA');
Bot.userAppeared = function (user) {
user = toID(user);
const mails = Bot.DB('mails').get(user);
if (!Bot.lmp) Bot.lmp = {};
if (!mails || !mails.length) return;
if (Bot.lmp[user] === mails.length) return;
Bot.lmp[user] = mails.length;
// eslint-disable-next-line max-len
Bot.pm(user, `You have ${mails.length} unread mail${mails.length === 1 ? '' : 's'} (from ${tools.listify([...new Set(mails.map(mail => mail.author))])})! Use \`\`${prefix}readmail\`\` to view ${mails.length === 1 ? 'it' : 'them'}!`);
};
Bot.teams = require('../data/DATA/teams.json');
Bot.hotpatch = require('../data/hotpatch.js');
Bot.watcher = require('./watcher.js')();
if (!Bot.seenBattles) Bot.seenBattles = new Set();
Bot.commandHandler = require('./commands.js');
GAMES.init();
},
chaterror: (room, message, isIntro) => {
// eslint-disable-next-line max-len
if (message.match(/^The user .*? is offline\.$/) || message === 'You do not have permission to use PM HTML to users who are not in this room.') return;
if (!isIntro) console.log('ERROR: ' + room + '> ' + message);
try {
client.channels.cache.get('719087165241425981').send('ERROR: ' + room + '> ' + message);
} catch {}
},
popup: (message) => console.log('POPUP: ' + message),
tour: (room, data) => {
require('./tours.js')(room, data, Bot);
},
join: (by, room, time) => {
Bot.userAppeared(by);
if (!Bot.jps[room] || !Bot.jps[room][by]) return;
if (Bot.jpcool[room][by] && (Bot.jpcool[room][by][0] < 10 || time - Bot.jpcool[room][by][1] < 3600000)) return;
Bot.say(room, Bot.jps[room][by]);
if (!Bot.jpcool[room]) Bot.jpcool[room] = {};
Bot.jpcool[room][by] = [0, time];
return;
},
nick: (by, old, room, time) => {
if (by === old) return;
DATABASE.see(old, new Date(time));
Bot.userAppeared(by);
DATABASE.alt(old, by);
},
leave: (by, room, time) => {
DATABASE.see(by, new Date(time));
return;
},
raw: (room, data, isIntro) => {
if (isIntro) return;
},
pmsuccess: (to, message) => { },
updatechallenges: data => {
try {
data = JSON.parse(data).challengesFrom;
for (const key in data) {
if (data[key] === 'gen8ou') {
if (!Bot.teams.gen8ou.length) {
Bot.pm(key, "Sorry, I don't have a team for OU.");
continue;
}
Bot.say('', '/utm ' + Bot.teams.gen8ou.random());
Bot.say('', '/accept ' + key);
Bot.log(`Fighting ${key}.`);
return;
} else Bot.pm(key, "Sorry, I only play [Gen 8] OU.");
}
} catch (e) {
Bot.log(e);
Bot.log(data);
}
},
queryresponse: info => {
info = info.split('|');
const type = info.shift();
if (type === 'roomlist') {
if (!Bot.rooms['2v2']) return;
try {
const rooms = JSON.parse(info.join('|')).rooms;
const batts = Object.keys(rooms);
batts.forEach(batt => {
if (Bot.seenBattles.has(batt)) return;
const battle = rooms[batt];
if (!battle.minElo || battle.minElo === 'tour') return; // don't report direct challenges / tour battles
const prefix = Bot.rooms['2v2']._ladderPrefix, floor = Bot.rooms['2v2']._ladderFloor;
if (floor && battle.minElo < floor) return; // Rating floor
if (prefix && !toID(battle.p1).startsWith(prefix) && !toID(battle.p2).startsWith(prefix)) return; // Ladder prefix
Bot.seenBattles.add(batt);
// eslint-disable-next-line max-len
Bot.say('2v2', `/addhtmlbox <span class="username">${tools.colourize(battle.p1)}</span> vs <span class="username">${tools.colourize(battle.p2)}</span>: «<a href="/${batt}" style="margin-top:25px;">${batt}</a>» (${battle.minElo})`);
});
} catch (e) {
Bot.log(e);
}
} else if (type === 'roominfo') {
try {
const room = JSON.parse(info.join('|'));
if (!Bot.rooms[room.id]) return;
if (room.id.startsWith('view-bot-')) return; // don't parse stuff from HTML rooms
Bot.rooms[room.id].type = room.visibility;
Bot.rooms[room.id].rank = room.users.find(u => toID(u) === toID(Bot.status.nickName))?.[0];
} catch (e) {
Bot.log(e);
Bot.log(info);
}
}
},
line: (room, message, isIntro) => {
if (message.charAt(0) === '>' || isIntro) return;
if (!Bot.streams[room]) return;
const stream = Bot.streams[room];
stream.write(`\n${message}`);
}
/* battle: (...args) => {
require('./battle.js').handler(...args);
}*/
};
<file_sep>/pmcommands/test.js
module.exports = {
help: `Pats a user.`,
permissions: 'gamma',
commandFunction: function (Bot, by, args, client) {
Bot.pm(by, `/me tests ${args.length ? args.join(' ') : by.substr(1)}`);
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/blitz.js
module.exports = {
cooldown: 1000,
help: `Creates a Tournament Blitz with the given options. Syntax: ${prefix}blitz (autostart / official (optional))`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
return Bot.pm(by, 'This command is under a constrictor! To avoid being swallowed by a snake, please append a ``7`` to the command and try again.');
if (args[1]) return Bot.say(room, unxa);
if (args[0].toLowerCase() === 'status' || args[0].toLowerCase() === 'show' || args[0].toLowerCase() === 'view' || args[0].toLowerCase() === 'display') {
if (!blitzObject[room].active && !blitzObject[room].prepping) return Bot.say(room, 'No Blitz is currently active.');
if (blitzObject[room].active) return Bot.say(room, 'A Blitz is currently active.');
return Bot.say(room, 'A Blitz will be starting, soon!');
}
if (args[0].toLowerCase() === 'end' || args[0].toLowerCase() == 'cancel') {
if (!blitzObject[room].active && !blitzObject[room].prepping) return Bot.say(room, "No Blitz is currently active.");
if (blitzObject[room].prepping) clearTimeout(blitzTimer);
blitzObject[room].prepping = false;
blitzObject[room].active = false;
blitzObject[room].autostart = false;
blitzObject[room].official = false;
blitzObject[room].starter = false;
return Bot.say(room, 'The Blitz has been cancelled.');
}
if (blitzObject[room].active || blitzObject[room].prepping) return Bot.say(room, 'A Blitz is already active.');
if (blitzObject[room]) {
blitzObject[room] = {
active: false,
prepping: false,
autostart: false,
official: false,
starter: false
};
}
if (args[0] && ['as', 'autostart'].includes(toID(args[0]))) blitzObject[room].autostart = true;
if (args[0] && ['o', 'official'].includes(args[0].toLowerCase())) {
blitzObject[room].official = true;
blitzObject[room].autostart = true;
}
blitzObject[room].starter = by.substr(1);
function startBlitz (room) {
if (!blitzObject[room]) return Bot.say(room, 'Something went wrong.');
blitzObject[room].prepping = false;
blitzObject[room].active = true;
Bot.say(room, '/wall The Blitz has started!');
}
const blitzTimer = setTimeout(startBlitz, 10000, room);
Bot.say(room, '/wall A Blitz will start in 10 seconds! Use ' + prefix + 'cast (type) to cast!');
blitzTimer;
blitzObject[room].prepping = true;
}
};
<file_sep>/pmcommands/dkr.js
module.exports = {
noDisplay: true,
help: `Starts the 4PM tour in Hindi.`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
if (!tools.hasPermission(by, 'beta', 'hindi')) return;
const hindi = Bot.rooms.hindi;
if (!hindi.tourPinged) return Bot.pm(by, "Not yet...");
if (hindi.tourPinged === 1) return Bot.pm(by, 'Sniped!');
hindi.tourPinged = 1;
Bot.say('hindi', '/changerankuhtml %, DkR, <button disabled>4 PM Tour</button>');
Bot.say('hindi', '/notifyoffrank %');
Bot.say('hindi', '~tour poll');
const timeLeft = 60 * 60 * 1000 - (Date.now() + 30 * 60 * 1000) % (60 * 60 * 1000);
setTimeout(() => {
Bot.say('hindi', `/notifyrank %, Tour start, Type ~tour start`);
Bot.say('hindi', `/addrankuhtml %, DkR, <button name="send" value="~tour start">Start!</button>`);
}, timeLeft);
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/parsetypes.js
module.exports = {
cooldown: 1,
help: ``,
permissions: 'admin',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args[0]) return Bot.say(room, unxa);
const type = toID(args.join(''));
if (!typelist.includes(type)) return Bot.say(room, 'Invalid type.');
const a = JSON.parse(fs.readFileSync('./data/DATA/newdex.json', 'utf8')), b = JSON.parse(fs.readFileSync('./data/DATA/formats.json', 'utf8')), c = Object.keys(a).filter(m => a[m].types.includes(tools.toName(type)) && b[m].isNonstandard != 'Past' && b[m].isNonstandard != 'CAP'), d = Object.keys(a).map(m => c.includes(m) ? '+' + a[m].species : '-' + a[m].species).join(', ');
fs.writeFileSync('./data/TOURS/CODES/TC/' + type + '.js', `exports.${type} = "/tour name Type Challenge: ${tools.toName(type)}!\\n/tour rules ${d}\\n/wall Type Challenge: ${tools.toName(type)}!";`);
return Bot.say(room, 'UwU');
}
};
<file_sep>/pmcommands/fuse.js
module.exports = {
help: `Ports two terms together. Syntax: ${prefix}fuse (term 1), (term 2)`,
permissions: 'coder',
commandFunction: function (Bot, by, args, client) {
let terms = args.join('').split(',');
const startTime = Date.now();
if (terms.length !== 2) return Bot.pm(by, unxa);
const toWord = {};
toWord[toID(terms[1])] = terms[1];
terms = terms.map(term => toID(term));
Object.values(data.pokedex).forEach(term => toWord[toID(term.name)] = term.name);
Object.values(data.moves).forEach(term => toWord[toID(term.name)] = term.name);
Object.values(data.items).map(term => {
return term.name.endsWith(' Berry') ? term.name.substr(0, term.name.length - 6) : term.name;
}).forEach(term => toWord[toID(term)] = term);
data.abilities.forEach(term => toWord[toID(term)] = term);
const words = Object.keys(toWord), first = terms[0], second = terms[1], neighbors = (word) => tools.getPorts(word, words)[1];
const wordTime = Date.now();
const preCheck = tools.getPorts(second, words)[0];
let flag = false, iteration = 1;
if (preCheck.length === 1) return Bot.pm(by, 'None found. :(');
const fObj = {};
let iter = new Set([first]);
fObj[first] = null;
while (true) {
if (iteration > 4) return Bot.pm(by, 'Overloaded!');
if (!iter.size) return Bot.pm(by, 'None found. :(');
const iterate = Array.from(iter);
iter = new Set();
for (const term of iterate) {
const runs = neighbors(term);
for (const run of runs) {
if (run === term) continue;
if (!fObj[run]) fObj[run] = term;
if (run === second) {
flag = true;
break;
}
iter.add(run);
}
if (flag) break;
}
if (flag) break;
iteration++;
}
let path = [], at = second;
while (at) {
path.unshift(at);
at = fObj[at];
}
path = path.map(term => {
if (toWord[term]) return toWord[term];
return tools.toName(term);
});
Bot.pm(by, path.join(', '));
Bot.pm(by, 'Runtime: ' + tools.toHumanTime(Date.now() - wordTime));
}
};
<file_sep>/commands/2v2/ladderfloor.js
module.exports = {
cooldown: 1000,
help: `Sets the ladder reporting floor; ie, the minimum Elo required to broadcast a match in the room.`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args.length) {
return Bot.say(room, `The current ladder floor is ${Bot.rooms[room]._ladderFloor || 1000} Elo.`);
}
const amt = parseFloat(args.join(' '));
if (!amt) {
delete Bot.rooms[room]._ladderFloor;
return Bot.say(room, 'The rating floor on ladder matches has been cleared.');
}
Bot.rooms[room]._ladderFloor = amt;
Bot.say(room, `The ladder floor has been set to ${amt} Elo - matches below this will not be broadcasted.`);
}
};
<file_sep>/discord/xkcd.js
module.exports = {
help: `Displays a random (or specified) xkcd.`,
pm: true,
commandFunction: function (args, message, Bot) {
const id = toID(args.join(''));
if (id) {
axios.get(`https://xkcd.com/${id}/info.0.json`)
.then(res => message.channel.send(`${res.data.safe_title} [#${id}]`).then(() => message.channel.send(res.data.img)))
.catch(() => message.channel.send(`That doesn't seem to look like a valid number for an xkcd comic...`));
} else {
axios.get('https://c.xkcd.com/random/comic/')
.then(res => axios.get(res.request.res.responseUrl + 'info.0.json'))
.then(res => {
message.channel.send(`${res.data.safe_title} [#${res.data.num}]`);
message.channel.send(res.data.img);
})
.catch(err => Bot.log(err) || message.channel.send(`Umm something went wrong whoops`));
}
}
};
<file_sep>/discord/puzzlers.js
const PZ = require('../data/PUZZLES/index.js');
module.exports = {
help: `Displays the status of each team.`,
guildOnly: PZ.guildID,
commandFunction: function (args, message, Bot) {
if (!message.member.roles.cache.has(PZ.IDs.staff)) {
return message.channel.send('Access denied.').then(msg => msg.delete({ timeout: 3000 }));
}
const Discord = require('discord.js'), embed = new Discord.MessageEmbed();
const input = toID(args.join(''));
embed
.setColor('#1ABC9C')
.setTitle('Puzzles Completed')
.addFields((input ? [args.join(' ').trim()] : PZ.allTeams().map(t => PZ.getTeam(t))).map(t => ({
name: t.name,
value: Object.keys(t.puzzles).filter(pzz => t.puzzles[pzz]).join(', ').trim() || '-'
})));
message.channel.send(embed);
}
};
<file_sep>/commands/pokemongo/raidpool.js
module.exports = {
cooldown: 0,
help: `Posts the current raid pool`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
// eslint-disable-next-line max-len
const images = ['https://cdn.discordapp.com/attachments/803693934139277383/906165674991292516/IMG_1208.png', 'https://cdn.discordapp.com/attachments/803693934139277383/900945591977250846/image0.png', 'https://cdn.discordapp.com/attachments/803693934139277383/897315451690967100/image0.png'];
const html = `<center><img src="${images.shift()}" height="400" width="414"/></center>`;
const voice = tools.hasPermission(by, 'gamma', room);
Bot.say(room, `/${voice ? 'add' : 'sendprivate'}uhtml ${voice ? '' : `${by}, `} RAIDPOOL, ${html}`);
}
};
<file_sep>/pmcommands/analyze.js
module.exports = {
help: `Analyzes a given hunt to return tags.`,
permissions: 'coder',
commandFunction: function (Bot, by, args, client) {
if (!args[0]) return Bot.pm(by, unxa);
let huntString = args.join(' ');
const huntPromise = new Promise((resolve, reject) => {
if (/pokepast\.es\/[a-z0-9]+(?:\/raw)?$/.test(huntString)) {
if (!/^https?:\/\//.test(huntString)) huntString = 'http://' + huntString;
if (!/\/raw$/.test(huntString)) huntString += '/raw';
require('request')(huntString, (error, response, body) => {
if (error) reject(error);
return resolve(body);
});
} else if (/pastebin\.com\/(?:raw\/)?[a-zA-Z0-9]+$/.test(huntString)) {
if (!/^https?:\/\//.test(huntString)) huntString = 'http://' + huntString;
if (!/\/raw/.test(huntString)) huntString = 'http://pastebin.com/raw/' + huntString.split('.com/')[1];
require('request')(huntString, (error, response, body) => {
if (error) reject(error);
return resolve(body);
});
} else if (/pastie\.io\/(?:raw\/)?[a-zA-Z0-9]+$/.test(huntString)) {
if (!/^https?:\/\/pastie\.io\/(?:raw\/)?[a-zA-Z0-9]+$/.test(huntString)) huntString = 'http://' + huntString;
if (!/\/raw/.test(huntString)) huntString = 'http://pastie.io/raw/' + huntString.split('.io/')[1];
require('request')(huntString, (error, response, body) => {
if (error) reject(error);
return resolve(body);
});
} else return resolve(huntString);
}).then(huntText => {
const aHunt = huntText.replace(/^(?:\/scav queue .*?\|)? ?/, '').split('|');
if (aHunt.length % 2) return Bot.pm(by, 'It appears that I found a question without an answer... :(');
const hunt = [];
while (aHunt.length) hunt.push({ q: aHunt.shift().trim(), a: aHunt.shift().split(';').map(a => a.trim()) });
hunt.forEach(q => {
q.tags = [];
if (/\brde\b/i.test(q.q)) q.tags.push('RDE');
if (/(?:\/n?ds)?.*?,/i.test(q.q) && /param(?:eter)?s/i.test(q.q)) q.tags.push('Params');
else {
const sp = q.q.split(', ');
let flag = true;
sp[0] = sp[0].split(' ').pop();
sp[sp.length - 1] = sp[sp.length - 1].split(' ').shift();
sp.forEach(m => {
if (!data.pokedex[toID(m)]) flag = false;
});
if (flag) q.tags.push('Params');
}
if (/(?:\[[^\[\]]*?\][^\+]*?){3,}/i.test(q.q)) q.tags.push('Port');
else if (/(?:\[[^\[\]]*?\].*?\+.*?)+(?:\[[^\[\]]*?\]*?)/i.test(q.q)) q.tags.push('Psywave');
// eslint-disable-next-line max-len
if (/(?:^|[\.,] ?)(?:\s*?(?:this|these|what) .*?(?:Pok.mon)?(?: is| was| are| were| ha(?:s|d|ve)| g[oe]t| learn|\'s')|Name (?:the|all))/i.test(q.q)) q.tags.push('Trivia');
});
function formatter (q) {
const out = {};
out['Discord Spoiler Format'] = `${q.q} | ||${q.a}||`;
out['Answerless Format'] = `${q.q} | REDACTED`;
out['Tagged Full Format'] = `[${q.tags.length ? tools.listify(q.tags) : 'Unidentified'}] ${q.q} | ${q.a}`;
return out;
}
const formatted = {};
hunt.forEach(q => {
const format = formatter(q);
Object.keys(format).forEach(type => {
if (!formatted[type]) formatted[type] = [];
formatted[type].push(format[type]);
});
});
Object.keys(formatted).forEach(type => formatted[type] = `/scav queue ${by.substr(1)} | ` + formatted[type].join(' | '));
let html = [];
const tags = Object.values(hunt).map(q => q.tags);
// eslint-disable-next-line max-len
html.push('<details><summary>Summary</summary><hr/>' + tags.map((q, i) => `Q${i + 1}) ${q.sort().join(', ')}`).join('<br/>') + '</details><hr/>');
Object.keys(formatted).forEach(type => html.push(`<details><summary>${type}</summary><hr/>${formatted[type]}</details>`));
html = html.join('<br/>');
return Bot.sendHTML(by, html);
}).catch(error => {
if (error) return Bot.pm(by, 'Invalid link!');
});
}
};
<file_sep>/commands/global/editjoinphrase.js
module.exports = {
cooldown: 10,
help: `Edits a joinphrase. Syntax: ${prefix}editjoinphrase (user), (joinphrase)`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
const cargs = args.join(' ').split(/,/);
if (!cargs[1]) return Bot.say(room, unxa);
const name = toID(cargs.shift());
if (!Bot.jps[room] || !Bot.jps[room][name]) {
return Bot.say(room, `It doesn\'t look like that user has a joinphrase... Try using ${prefix}addjoinphrase instead?`);
}
if (Bot.rooms[room].shop?.jpl?.length && !Bot.rooms[room].shop.jpl.includes(name)) {
return Bot.say(room, `They don't have a license, though. That's illegal. :(`);
}
let jp = cargs.join(',').trim();
if (/(?:kick|punt)s? .*\bSnom\b/i.test(jp)) return Bot.say(room, `Unacceptable.`);
if (/^\/[^\/]/.test(jp) && !/^\/mee? /.test(jp)) jp = '/' + jp;
if (/^!/.test(jp) && !/^!n?da?(?:ta?|s) /.test(jp)) jp = ' ' + jp;
Bot.jps[room][name] = jp;
fs.writeFile(`./data/JPS/${room}.json`, JSON.stringify(Bot.jps[room], null, 2), e => {
if (e) return console.log(e);
Bot.say(room, 'Joinphrase edited!');
});
}
};
<file_sep>/commands/global/addleaderboard.js
// TODO: Use room config instead
/* eslint-disable no-unreachable */
module.exports = {
cooldown: 6000,
// eslint-disable-next-line max-len
help: `Adds a leaderboard for the room. Syntax: ${prefix}addleaderboard n, ...words - n is the number of currencies, and words are the standard labels.`,
permissions: 'coder',
commandFunction: function (Bot, room, time, by, args, client) {
return Bot.say(room, `Yeeted. Use configs!`);
if (Bot.rooms[room].lb) return Bot.say(room, 'This room already has a leaderboard!');
const data = { users: {}, points: [] };
args = args.join(' ').split(/\s*,\s*/);
if (!args.length) return Bot.say(room, unxa);
const n = parseInt(args.shift());
if (isNaN(n)) return Bot.say(room, this.help);
if (args.length !== 3 * n) {
return Bot.say(room, "You need to specify all three labels for each currency! (singular, plural, abbreviated)");
}
args = args.map(arg => arg.replace(/</g, '<').replace(/>/g, '>'));
for (let i = 0; i < n; i++) data.points.push(args.splice(0, 3));
fs.writeFile(`./data/POINTS/${room}.json`, JSON.stringify(data, null, 2), e => {
if (e) {
console.log(e);
Bot.log(e);
Bot.say(room, e.message);
return;
}
Bot.say(room, 'Leaderboard added!');
tools.loadLB(room);
});
}
};
<file_sep>/pmcommands/filtermoves.js
module.exports = {
cooldown: 1000,
help: `Filters through all Pokemon moves using RegExp. Tutorial: https://regexone.com/lesson/introduction_abcs`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
try {
const regex = new RegExp(args.join(' ').trim().replace(/\s*$/g, ''), 'i');
const out = Object.keys(data.moves).filter(m => regex.test(m));
if (!out.length) return Bot.pm(by, 'None.');
// eslint-disable-next-line max-len
return Bot.sendHTML(by, `<details><summary>Results (${out.length})</summary>` + out.map(m => data.moves[m].name).sort().join('<br>') + '</details>');
} catch {
Bot.pm(by, "RegEx doesn't work that way - try taking a look at https://regexone.com/lesson/introduction_abcs");
}
}
};
<file_sep>/discord/wolframalpha.js
module.exports = {
help: `Queries the WolframAlpha database. Please use sparingly. Remember, you are responsible for the output of this command.`,
pm: true,
commandFunction: function (args, message, Bot) {
const token = require('../../config.js').wolframToken;
// To anyone who reads this code
// I sincerely apologize
const query = args.join(' ');
axios.get(`http://api.wolframalpha.com/v2/query?appid=${token}&input=${query}&format=plaintext,image`).then(res => {
const info = res.data, img = info.match(/<img src=(['"]).*?\1/);
let imgt;
const txt = info.match(/<plaintext>.*?<\/plaintext>/g);
const Discord = require('discord.js'), embed = new Discord.MessageEmbed().setColor('#FF4500');
if (!txt && !img) {
Bot.log(info);
return message.channel.send("Nothing found.");
}
embed.setTitle("Result: ");
if (txt) {
// eslint-disable-next-line max-len
embed.addField('\u200b', tools.unescapeHTML(txt.join('\n').replace(/<\/?plaintext>/g, '').replace(/@(?:everyone|here)/g, match => '@\u200b' + match.substr(1))));
}
if (img) embed.setImage(imgt = tools.unescapeHTML(img[0].substr(10).split(/['"]/)[0]));
message.channel.send(embed);
}).catch(err => {
message.channel.send("Sorry, nothing found!");
Bot.log(err);
});
}
};
<file_sep>/commands/pokemongo/setuser.js
module.exports = {
cooldown: 0,
help: `Configures your PoGo info. Syntax: ${prefix}setuser (entry1): (value1), (entry2): (value2)...`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client, isFrom) {
const protoDB = require('origindb')('data/POGO'), DB = protoDB('users');
const username = toID(by), displayName = by.substr(1);
const user = DB.get(username) || { raids: {} };
if (username === 'constructor') return Bot.pm(isFrom, `...can you not, please?`);
user.username = username;
user.displayName = displayName;
const validEntries = ['code', 'ign', 'level'];
const entries = args
.join(' ')
.replace(/[^a-zA-Z0-9,:]/g, '')
.split(',')
.filter(k => k.indexOf(':') >= 0)
.map(k => k.split(':', 2))
.filter(k => k[1])
.map(k => [k[0].toLowerCase(), k[1]]);
for (const entry of entries) {
if (!validEntries.includes(entry[0])) {
return Bot.roomReply(room, by, `Sorry, that wasn't a valid entry! Valid entries are: ${validEntries.join(', ')}`);
}
user[entry[0]] = entry[1];
}
const missing = validEntries.find(entry => !user.hasOwnProperty(entry));
if (missing) return Bot.roomReply(room, by, `You're missing a required entry (${missing})`);
if (!/^\d{12}$/.test(user.code)) return Bot.roomReply(room, by, `Your given FC (${user.code}) was invalid`);
if (!/^(?:50|[1-4][0-9]|[5-9])$/.test(user.level)) {
return Bot.roomReply(room, by, `Your given level (${user.level}) was invalid`);
}
DB.set(username, user);
// eslint-disable-next-line max-len
Bot.say(room, `/sendprivatehtmlbox ${isFrom || by}, ${tools.escapeHTML(user.displayName)}'s profile is: ${[user.ign, ` (Lv ${user.level})`, ` [FC: ${user.code}]`].map(tools.unescapeHTML).join('')}`);
}
};
<file_sep>/commands/global/scope.js
module.exports = {
cooldown: 10000,
help: `Displays the room(s) where a command can be used. Syntax: ${prefix}scope (command)`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args[0]) return Bot.say(room, unxa);
const commandName = tools.commandAlias(toID(args.join('')));
const commandObj = {};
fs.readdir('./commands', (e, rooms) => {
if (e) return console.log(e);
rooms.filter(folder => !folder.includes('.')).forEach(folder => {
commandObj[folder] = [];
fs.readdirSync('./commands/' + folder)
.filter(comm => comm.endsWith('.js'))
.map(comm => comm.substr(0, comm.length - 3))
.forEach(comm => commandObj[folder].push(comm));
});
const foundRooms = [];
for (const prop in commandObj) {
if (commandObj[prop].includes(commandName)) foundRooms.push(prop);
}
if (!foundRooms.length) return Bot.say(room, 'It doesn\'t look like the ' + commandName + ' command exists.');
if (foundRooms.includes('global')) return Bot.say(room, 'The ' + commandName + ' command is global.');
return Bot.say(room, 'The ' + commandName + ' command can be used in ' + tools.listify(foundRooms) + '.');
});
}
};
<file_sep>/data/GAMES/chainreaction.js
class CR {
constructor (height, width, room, beeg) {
this.room = room;
if (!width || !height) {
width = 6;
height = 9;
}
this.height = height;
this.width = width;
this.beeg = beeg;
this.board = Array.from(Array(height).keys()).map(x => Array.from(Array(width).keys()).map(y => ({
value: 0,
crit: Array.from([x, y, height - x - 1, width - y - 1]).filter(n => n).length,
col: 0,
coords: [x, y]
})));
this.colours = {};
this.players = {};
this.started = false;
this.order = [];
this.PL = [];
this.turn = null;
if (beeg) this.availableColours = [
'#e6194b',
'#3cb44b',
'#ffe119',
'#4363d8',
'#f58231',
'#911eb4',
'#42d4f4',
'#f032e6',
'#bfef45',
'#fabed4',
'#dcbeff',
'#fffac8',
'#aaffc3',
'#ffffff',
'#a9a9a9'
].shuffle();
else this.availableColours = [
'#ff0000',
'#ff8000',
'#ffff00',
'#00ff00',
'#00ffff',
'#0000ff',
'#9e00ff',
'#ff00ff'
].shuffle();
this.displaying = false;
}
addPlayer (name) {
const user = toID(name), colour = this.availableColours.pop();
if (!colour) return null;
if (this.players[user]) return;
this.players[user] = {
name: name,
col: colour,
played: false
};
this.colours[colour] = user;
this.order.push(user);
this.PL.push(user);
return true;
}
removePlayer (name) {
const user = toID(name);
if (!this.players[user]) return;
this.availableColours.push(this.players[user].col);
this.order.remove(user);
this.PL.remove(user);
delete this.colours[this.players[user].col];
delete this.players[user];
return true;
}
start () {
if (this.started) return;
this.started = true;
this.order.shuffle();
Bot.say(this.room, `The game of Chain Reaction is starting!`);
this.turn = this.order[this.order.length - 1];
return this.nextTurn();
}
nextTurn () {
if (!this.started || !this.turn || !this.order.includes(this.turn)) return;
const allO = Array.from(this.order);
if (this.turn === this.order[this.order.length - 1]) this.turn = this.order[0];
else this.turn = this.order[this.order.indexOf(this.turn) + 1];
this.order = this.order.filter(player => this.isAlive(player));
if (this.order.length < 2) return this.order[0];
while (!this.order.includes(this.turn)) {
if (this.turn === allO[allO.length - 1]) this.turn = allO[0];
else this.turn = allO[allO.indexOf(this.turn) + 1];
}
Bot.say(this.room, `/adduhtml CR, ${this.display()}`);
return Bot.say(this.room, `/notifyuser ${this.turn}, Chain Reaction, Your turn!`);
}
isAlive (player) {
const user = toID(player);
if (!this.players[user]) return false;
if (!this.players[user].played) return true;
const col = this.players[user].col;
for (let i = 0; i < this.height; i++) for (let j = 0; j < this.width; j++) {
if (this.board[i][j].value && this.board[i][j].col === col) return true;
}
return false;
}
willExplode (board) {
if (!board) board = this.board;
for (let i = 0; i < this.height; i++) for (let j = 0; j < this.width; j++) {
if (board[i][j].value >= board[i][j].crit) return true;
}
return false;
}
detonate (board) {
if (!board) board = this.board;
const clone = JSON.parse(JSON.stringify(board));
if (!this.willExplode(clone)) return;
for (let i = 0; i < this.height; i++) for (let j = 0; j < this.width; j++) {
if (clone[i][j].value >= clone[i][j].crit) {
board[i][j].value -= board[i][j].crit;
[[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]].filter(cell => {
return cell[0] >= 0 && cell[0] < this.height && cell[1] >= 0 && cell[1] < this.width;
}).forEach(cell => {
board[cell[0]][cell[1]].value++;
board[cell[0]][cell[1]].col = board[i][j].col;
});
if (!board[i][j].value) board[i][j].col = 0;
}
}
return this.willExplode();
}
tap (x, y, col) {
if (x >= this.height || x < 0 || y >= this.width || y < 0 || !this.colours[col]) return;
if (this.board[x][y].value && this.board[x][y].col !== col) return;
this.players[this.colours[col]].played = true;
const out = [];
if (!this.board[x][y].value) this.board[x][y].col = col;
this.board[x][y].value++;
out.push(this.display());
while (this.willExplode() && this.order.filter(player => this.isAlive(player)).length > 1) {
this.detonate(Array.from(this.board));
out.push(this.display(true));
}
return [...out, this.display()];
}
display (filler) {
// eslint-disable-next-line max-len
let html = '<div style="background-color: black;"><center><table style="border-collapse:collapse;border-spacing:0;border-color:#aaa;" border="1">';
const a = "25";
for (let i = 0; i < this.height; i++) {
html += `<tr>`;
for (let j = 0; j < this.width; j++) {
// eslint-disable-next-line max-len
html += `<td width="${a}" height="${a}" style="text-align:center;">${filler ? '' : `<b><button name="send" value="/msgroom ${this.room},/botmsg ${Bot.status.nickName}, ${prefix}chainreaction ${this.room} click ${i} ${j}" style="background:none;border:none;width:100%;height:100%;"${this.board[i][j].col ? ` title="${tools.escapeHTML(this.players[this.colours[this.board[i][j].col]].name)}"` : ''}>`}<span style="color:${this.board[i][j].col};font-family:Verdana;">${this.board[i][j].value || ' '}</span>${filler ? '' : '</button></b>'}</td>`;
}
html += '</tr>';
}
// eslint-disable-next-line max-len
html += `</table></center></div><br>Current turn: <font color="${this.players[this.turn].col}">@</font>${tools.escapeHTML(this.players[this.turn].name)}`;
return html;
}
}
module.exports = CR;
<file_sep>/data/VR/TC7/ground.js
exports.ground = {
sp: ["Mamoswine", "Landorus-Incarnate", "Landorus-Therian"],
s: ["Torterra"],
sm: ["Seismitoad", "Zygarde-Complete"],
ap: ["Swampert", "Swampert-Mega", "Quagsire"],
a: ["Steelix-Mega", ""],
am: ["Donphan", "Gastrodon"],
bp: ["Silvally-Ground"],
b: ["Piloswine", "Garchomp", "Diggersby", "Marshtomp"],
bm: ["Excadrill"],
cp: [],
c: ["Mudsdale"],
cm: ["Flygon"],
d: ["Garchomp-Mega", "Camerupt-Mega", "Gliscor"],
e: ["Stunfisk", "Dugtrio", "Golem", "Rhyperior", "Wormadam-Sandy"],
unt: ["Hippowdon", "Claydol", "Whiscash"],
bans: ["None"]
};
<file_sep>/pmcommands/filtername.js
module.exports = {
cooldown: 1000,
help: `Filters through all Pokemon names using RegExp. Tutorial: https://regexone.com/lesson/introduction_abcs`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
let regex;
try {
regex = new RegExp(args.join(' ').trim(), 'i');
const out = Object.keys(data.pokedex).filter(m => data.pokedex[m].num > 0 && regex.test(m));
if (!out.length) return Bot.pm(by, 'None.');
// eslint-disable-next-line max-len
return Bot.sendHTML(by, `<details style="font-family:\'Arial\',monospace;"><summary>Results (${out.length})</summary>` + out.map(m => data.pokedex[m].name).sort().join('<br>') + '</details>');
} catch (e) {
Bot.pm(by, e.message);
}
}
};
<file_sep>/data/VR/TC7/ice.js
exports.ice = {
sp: ["Crabominable"],
s: ["Weavile", "Mamoswine"],
sm: ["Ninetales-Alola", "Avalugg"],
ap: ["Sandslash-Alola"],
a: ["Sealeo", "Walrein"],
am: ["Cloyster"],
bp: ["Jynx"],
b: ["Rotom-Frost", "Froslass"],
bm: [],
cp: ["Piloswine"],
c: ["Glalie-Mega"],
cm: ["Dewgong"],
d: [],
e: [],
unt: [],
bans: ["Kyurem"]
};
<file_sep>/commands/botdevelopment/test.js
module.exports = {
cooldown: 0,
help: `Testing stuff.`,
permissions: 'coder',
commandFunction: function (Bot, room, time, by, args, client, redir = false) {
const pkmn = toID(args.join('')) || 'zacian';
const mon = data.unitedex.find(m => toID(m.name) === pkmn);
const lv = 15;
const stats = data.unitestats.find(m => m.name === mon.name).level[lv - 1];
const hst = { ...data.unitestats[0].level[lv - 1] };
data.unitestats.forEach(stat => {
Object.entries(stat.level[lv - 1]).forEach(([k, v]) => {
if (hst[k] < v) hst[k] = v;
});
});
nunjucks.render('unite/character.njk', { mon, lv, hst, stats, redir }, (e, html) => {
if (e) console.log(e);
else Bot.say(room, `!htmlbox ${html}`);
});
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/blitz7.js
module.exports = {
cooldown: 1000,
help: `Creates a Tournament Blitz with the given options. Syntax: ${prefix}blitz (autostart / official (optional))`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
if (args[1]) return Bot.say(room, unxa);
if (!Bot.rooms[room].blitzObject) {
Bot.rooms[room].blitzObject = {
active: false,
prepping: false,
autostart: false,
official: false,
starter: false,
gen: 0
};
}
if (args[0] && (args[0].toLowerCase() === 'status' || args[0].toLowerCase() === 'show' || args[0].toLowerCase() === 'view' || args[0].toLowerCase() === 'display')) {
if (!Bot.rooms[room].blitzObject.active && !Bot.rooms[room].blitzObject.prepping) return Bot.say(room, 'No Blitz is currently active.');
if (Bot.rooms[room].blitzObject.active) return Bot.say(room, 'A Blitz is currently active.');
return Bot.say(room, 'A Blitz will be starting, soon!');
}
if (args[0] && (args[0].toLowerCase() === 'end' || args[0].toLowerCase() == 'cancel')) {
if (!Bot.rooms[room].blitzObject.active && !Bot.rooms[room].blitzObject.prepping) return Bot.say(room, "No Blitz is currently active.");
if (Bot.rooms[room].blitzObject.prepping) clearTimeout(Bot.roms[room].blitzTimer);
delete Bot.rooms[room].blitzObject;
return Bot.say(room, 'The Blitz has been cancelled.');
}
if (Bot.rooms[room].blitzObject.active || Bot.rooms[room].blitzObject.prepping) return Bot.say(room, 'A Blitz is already active.');
if (Bot.rooms[room].blitzObject) {
Bot.rooms[room].blitzObject = {
active: false,
prepping: false,
autostart: false,
official: false,
starter: false,
gen: 7
};
}
if (args[0] && ['as', 'autostart'].includes(toID(args[0]))) Bot.rooms[room].blitzObject.autostart = true;
if (args[0] && ['o', 'official'].includes(args[0].toLowerCase())) {
Bot.rooms[room].blitzObject.official = true;
Bot.rooms[room].blitzObject.autostart = true;
}
Bot.rooms[room].blitzObject.starter = by.substr(1);
function startBlitz (room) {
if (!Bot.rooms[room].blitzObject) return Bot.say(room, 'Something went wrong.');
Bot.rooms[room].blitzObject.prepping = false;
Bot.rooms[room].blitzObject.active = true;
Bot.say(room, '/wall The Blitz has started!');
delete Bot.rooms[room].blitzTimer;
}
Bot.rooms[room].blitzTimer = setTimeout(startBlitz, 1000, room);
Bot.say(room, '/wall A Blitz will start in 10 seconds! Use ' + prefix + 'cast (type) to cast!');
Bot.rooms[room].blitzObject.prepping = true;
}
};
<file_sep>/commands/pokemongo/pingraid.js
module.exports = {
cooldown: 0,
help: `Pings everyone in a raid.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
const user = toID(by);
const raids = Bot.rooms[room].raids || {};
if (!Object.keys(raids).length) return Bot.pm(by, "No raids are active, whoops");
const host = toID(args.join('')) || user;
if (!raids.hasOwnProperty(host)) return Bot.pm(by, `T-that user isn't hosting? I think?`);
if (!tools.hasPermission(by, 'gamma', room) && host !== user) {
return Bot.pm(by, 'Access DENIED - you may not ping for another user\'s raid!');
}
const raid = raids[host];
const pings = Object.values(raid.players);
if (!pings.length) return Bot.say(room, `B-but no one even joined D:`);
Bot.say(room, `/wall Raid time! Pinging ${tools.listify(pings)}`);
Bot.commandHandler('lockraid', by, args, room, true);
}
};
<file_sep>/commands/global/blackjack.js
// TODO: Migrate to /data/GAMES
// TODO: Use HTML pages
module.exports = {
cooldown: 1,
help: `The Blackjack module. Syntax: ${prefix}blackjack (new | start | join | help | end)`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args.length) args.push('help');
switch (args.shift().toLowerCase()) {
case 'help': case 'h': {
const help = `The aim of the game is to get more than the dealer and win. However, if your score exceeds 21, you 'bust' and lose. Cards 2-10 have their face values; J, Q, and K are 10 apiece, and A can be 1 or 11. Use ${prefix}hit to draw another card, ${prefix}stay to end, or ${prefix}hand to see your cards.`;
if (tools.hasPermission(by, 'gamma', room)) return Bot.say(room, help);
else return Bot.roomReply(room, by, help);
break;
}
case 'new': case 'n': case 'create': case 'c': {
if (!tools.hasPermission(by, 'beta', room)) return Bot.roomReply(room, by, 'Access denied.');
if (Bot.rooms[room].blackjack) return Bot.say(room, `A game of Blackjack is in signups! Use \`\`${prefix}blackjack join\`\` to join!`);
Bot.rooms[room].blackjack = {
players: {},
started: false,
dealer: [],
turn: null,
start: (room) => {
if (Bot.rooms[room].blackjack.started) return;
if (!Bot.rooms[room].blackjack) return;
if (!Object.keys(Bot.rooms[room].blackjack.players).length) {
Bot.say(room, 'Not enough players. :(');
return delete Bot.rooms[room].blackjack;
}
Bot.rooms[room].blackjack.started = true;
Bot.rooms[room].blackjack.deck = tools.newDeck(null, 2).shuffle();
Bot.rooms[room].blackjack.dealer.push(Bot.rooms[room].blackjack.deck.pop());
Bot.rooms[room].blackjack.dealer.push(Bot.rooms[room].blackjack.deck.pop());
const str = [];
Object.keys(Bot.rooms[room].blackjack.players).forEach(player => {
Bot.rooms[room].blackjack.players[player].cards.push(Bot.rooms[room].blackjack.deck.pop());
Bot.rooms[room].blackjack.players[player].cards.push(Bot.rooms[room].blackjack.deck.pop());
str.push(` ${Bot.rooms[room].blackjack.players[player].name}'s: ${tools.cardFrom(Bot.rooms[room].blackjack.players[player].cards[0]).join('')}`);
});
Bot.say(room, 'Top cards: ' + str.join(', '));
Bot.say(room, `The Dealer's top card: ${tools.cardFrom(Bot.rooms[room].blackjack.dealer[0]).join('')}`);
return Bot.rooms[room].blackjack.nextTurn(room);
},
nextTurn (room) {
const players = Object.keys(Bot.rooms[room].blackjack.players);
if (!Bot.rooms[room].blackjack.turn) Bot.rooms[room].blackjack.turn = players[0];
else if (Bot.rooms[room].blackjack.turn !== players[players.length - 1]) Bot.rooms[room].blackjack.turn = players[players.indexOf(Bot.rooms[room].blackjack.turn) + 1];
else {
while (tools.sumBJ(Bot.rooms[room].blackjack.dealer) < 17) Bot.rooms[room].blackjack.dealer.push(Bot.rooms[room].blackjack.deck.pop());
let score = tools.sumBJ(Bot.rooms[room].blackjack.dealer);
if (tools.sumBJ(Bot.rooms[room].blackjack.dealer) > 21) {
Bot.say(room, `The dealer has busted with ${score}! (${Bot.rooms[room].blackjack.dealer.map(card => tools.cardFrom(card).join('')).join(', ')})`);
score = 0;
} else Bot.say(room, `The dealer has ${score}! (${Bot.rooms[room].blackjack.dealer.map(card => tools.cardFrom(card).join('')).join(', ')})`);
const winners = Object.keys(Bot.rooms[room].blackjack.players).filter(player => tools.sumBJ(Bot.rooms[room].blackjack.players[player].cards) > score && !Bot.rooms[room].blackjack.players[player].busted).map(player => Bot.rooms[room].blackjack.players[player].name);
Bot.say(room, `Winners: ${winners.length ? tools.listify(winners) : 'None'}!`);
const nbj = winners.filter(player => Bot.rooms[room].blackjack.players[toID(player)].nbj);
if (nbj.length) Bot.say(room, `${tools.listify(nbj)} ${nbj.length == 1 ? 'has' : 'have'} a natural Blackjack!`);
nbj.forEach(player => tools.addPoints(0, player, 5, room));
winners.forEach(player => tools.addPoints(0, player, 5, room));
return delete Bot.rooms[room].blackjack;
}
if (Bot.rooms[room].blackjack.timer) clearInterval(Bot.rooms[room].blackjack.timer);
Bot.rooms[room].blackjack.timer = setTimeout(room => {
if (!room) return;
if (!Bot.rooms[room].blackjack || !Bot.rooms[room].blackjack.players[Bot.rooms[room].blackjack.turn]) return;
Bot.say(room, `${Bot.rooms[room].blackjack.players[Bot.rooms[room].blackjack.turn].name} was force-stayed.`);
Bot.commandHandler('stay', ' ' + Bot.rooms[room].blackjack.turn, [], room);
}, 60000, room);
Bot.say(room, ` ${Bot.rooms[room].blackjack.players[Bot.rooms[room].blackjack.turn].name}'${Bot.rooms[room].blackjack.turn.endsWith('s') ? '' : 's'} turn! Use \`\`${prefix}hit\`\` or \`\`${prefix}stay\`\`!`);
return Bot.roomReply(room, Bot.rooms[room].blackjack.turn, `Your cards: ${Bot.rooms[room].blackjack.players[Bot.rooms[room].blackjack.turn].cards.map(card => tools.cardFrom(card).join('')).join(', ')}. Your current sum: ${tools.sumBJ(Bot.rooms[room].blackjack.players[Bot.rooms[room].blackjack.turn].cards)}`);
}
};
if (args.length) {
const time = parseInt(args.join('').replace(/[^0-9]/g, ''));
if (!isNaN(time) && time >= 20 && time <= 120) {
setTimeout(Bot.rooms[room].blackjack.start, time * 1000, room);
return Bot.say(room, `A game of Blackjack has been created! Use \`\`${prefix}blackjack join\`\` to join in the next ${time} seconds!`);
}
}
return Bot.say(room, `A game of Blackjack has been created! Use \`\`${prefix}blackjack join\`\` to join!`);
break;
}
case 'join': case 'j': {
if (!Bot.rooms[room].blackjack) return Bot.say(room, `There isn't a game of Blackjack active...`);
if (Bot.rooms[room].blackjack[toID(by)]) return Bot.roomReply(room, by, `You've already joined!`);
if (Bot.rooms[room].blackjack.started) return Bot.roomReply(room, by, 'It already started, F.');
Bot.rooms[room].blackjack.players[toID(by)] = {
name: by.substr(1),
cards: []
};
return Bot.roomReply(room, by, `You have joined the game of Blackjack in ${Bot.rooms[room].title}.`);
break;
}
case 'start': case 's': {
if (!tools.hasPermission(by, 'beta', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].blackjack) return Bot.say(room, `There isn't a game of Blackjack active...`);
Bot.rooms[room].blackjack.start(room);
return;
break;
}
case 'skip': {
if (!tools.hasPermission(by, 'beta', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].blackjack) return Bot.say(room, `There isn't a game of Blackjack active...`);
if (!Bot.rooms[room].blackjack.started) return Bot.say(room, 'Nope, hasn\'t started, yet.');
Bot.rooms[room].blackjack.nextTurn();
return;
break;
}
case 'end': case 'e': {
if (!tools.hasPermission(by, 'beta', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].blackjack) return Bot.say(room, 'Blackjack wasn\'t even ongoing, :eyes:.');
delete Bot.rooms[room].blackjack;
return Bot.say(room, 'The game of Blackjack has ended! No points will be awarded.');
break;
}
default: {
return Bot.roomReply(room, by, `That isn't an option...`);
break;
}
}
}
};
<file_sep>/commands/global/hand.js
// TODO: Migrate to a blackjack subcommand
module.exports = {
cooldown: 10,
help: `Displays your hand. Syntax: ${prefix}hand`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
if (Bot.rooms[room].blackjack) {
if (!Bot.rooms[room].blackjack.players[toID(by)]) return Bot.pm(by, 'You\'re not in the game!');
const cards = Bot.rooms[room].blackjack.players[toID(by)].cards;
return Bot.pm(by, `Your hand: ${cards.map(card => tools.cardFrom(card).join('')).join(', ')}`);
} else if (Bot.rooms[room].ev) {
if (!Bot.rooms[room].ev.players[toID(by)]) return Bot.pm(by, 'You\'re not in the game!');
return Bot.sendHTML(by, tools.handHTML(Bot.rooms[room].ev.players[toID(by)].cards));
} else return Bot.pm(by, 'Nope, no games found.');
}
};
<file_sep>/discord/hplupdate.js
module.exports = {
help: `Collection of HPL links.`,
guildOnly: '729992843925520474',
commandFunction: function (args, message, Bot) {
if (!message.member.roles.cache.find(r => r.id === '729994253865844806')) {
return message.channel.send('ACCESS DENIED - why do you know about this :sus:').then(msg => msg.delete({ timeout: 3000 }));
}
delete require.cache[require.resolve('../data/DATA/hplsheet.js')];
require('../data/DATA/hplsheet.js')().then(res => message.channel.send(res.join(', '))).catch(err => {
Bot.log(err);
message.channel.send(err.message || err);
});
}
};
<file_sep>/discord/litwick.js
module.exports = {
help: `Toggles the Litwick role.`,
guildOnly: "854760340159070210",
commandFunction: function (args, message, Bot) {
if (message.member.roles.cache.find(r => r.id === '854767136077250561')) {
message.member.roles.remove(message.guild.roles.cache.get("854767136077250561")).then(() => {
message.channel.send('o/, former Litwick.');
}).catch(Bot.log);
} else message.member.roles.add(message.guild.roles.cache.get("854767136077250561")).then(() => {
message.channel.send('Welcome to the Litwick!');
}).catch(Bot.log);
}
};
<file_sep>/data/GAMES/mastermind.js
class Mastermind {
constructor (room, user, guessLimit) {
this.name = user.replace(/^[^a-z0-9A-Z]/, '');
this.player = toID(user);
this.guessLimit = guessLimit || 10;
this.room = room;
this.colours = [
{
colour: "white",
text: "black",
index: 0
},
{
colour: "red",
text: "white",
index: 1
},
{
colour: "orange",
text: "black",
index: 2
},
{
colour: "yellow",
text: "black",
index: 3
},
{
colour: "green",
text: "white",
index: 4
},
{
colour: "blue",
text: "white",
index: 5
},
{
colour: "purple",
text: "white",
index: 6
},
{
colour: "pink",
text: "black",
index: 7
}
];
this.sol = Array.from({ length: 4 }).map(t => Math.floor(Math.random() * 8));
this.guesses = [];
this.spectators = [];
}
guess (input) {
const self = this;
return new Promise((resolve, reject) => {
if (!Array.isArray(input)) input = String(input).replace(/[^\d]/g, '').split('');
input = input.map(num => parseInt(num));
if (input.length !== 4) return reject("Guess must be 4 numbers long!");
let sol = JSON.parse(JSON.stringify(self.sol)), guess = JSON.parse(JSON.stringify(input)), close = 0;
const hits = [];
for (let i = 0; i < 4; i++) {
if (sol[i] === guess[i]) hits.push(i);
}
sol = sol.filter((t, i) => !hits.includes(i)).sort((a, b) => a - b);
guess = guess.filter((t, i) => !hits.includes(i)).sort((a, b) => a - b);
for (let i = 0; i < sol.length; i++) {
while (sol.includes(guess[i])) {
sol.remove(guess[i]);
guess.remove(guess[i]);
close++;
}
}
const temp = self.guesses.pop();
if (temp && temp[4][0] !== null) self.guesses.push(temp);
self.guesses.push([...input, [hits.length, close]]);
if (hits.length === 4) return resolve(1);
if (self.guesses.length >= self.guessLimit) return resolve(2);
return resolve(0);
});
}
type (num) {
num = parseInt(num);
if (typeof num !== 'number') return null;
if (num < 0 || num >= this.colours.length) return null;
let lastGuess = this.guesses[this.guesses.length - 1];
if (!lastGuess || lastGuess[4] && lastGuess[4][0] !== null) {
this.guesses.push([null, null, null, null, [null]]);
lastGuess = this.guesses[this.guesses.length - 1];
}
for (let i = 0; i < 4; i++) {
if (lastGuess[i] !== null && i !== 3) continue;
lastGuess[i] = num;
break;
}
return true;
}
backspace () {
const lastGuess = this.guesses[this.guesses.length - 1];
if (!lastGuess || lastGuess[4][0] !== null) return false;
for (let i = 0; i < 4; i++) {
if (lastGuess[i] === null) {
lastGuess[i - 1] = null;
return true;
}
}
lastGuess[3] = null;
return true;
}
boardHTML (player) {
const scale = 3.5;
// eslint-disable-next-line max-len
let html = `<div style="margin-left: 50px; margin-top: 20px; width: ${76 * scale};"><div style="margin: auto; width: ${76 * scale}px; background: #222222; border: 2px solid black; margin-top: 5px; display: inline-block;">`;
// eslint-disable-next-line max-len
html += `<div style="margin-left: ${5 * scale}px; margin-right: ${22 * scale}px; margin-top: ${4 * scale}px; margin-bottom: ${4 * scale}px; background: #111111; border: 1px solid black; font-size: ${0.5 * scale}em; font-weight: bold; color: red; text-align: center; display: table;">${Array.from({ length: 4 }).map(() => `<div style="display: table-cell; width: ${10 * scale}px; height: ${10 * scale}px; margin-left: margin-right: ${2 * scale}px; vertical-align: middle;">?</div>`).join('')}</div>`;
for (let i = this.guessLimit - 1; i >= 0; i--) {
// eslint-disable-next-line max-len
html += `<hr style="color: black; padding-top: padding-bottom: ${2 * scale}px; margin-left: margin-right: ${5 * scale}px;">`;
// eslint-disable-next-line max-len
html += `<div style="display: inline-block; margin-top: ${2 * scale}; margin-bottom: ${2 * scale}px; height: ${10 * scale}px; vertical-align: middle; text-align: left;">${(this.guesses[i] || [null, null, null, null, [null]]).slice(0, 4).map((n, index) => {
// eslint-disable-next-line max-len
if (typeof n !== 'number') return `<div style="display: inline-block; margin-left: ${2 * scale}px; margin-right: ${2 * scale}px; margin-top: margin-bottom: ${2 * scale}px; width: ${10 * scale}px; height: ${10 * scale}px; border-radius: 50%; background: none; vertical-align: middle;"> </div>`;
// eslint-disable-next-line max-len
else return `<div style="display: inline-block; margin-left: ${2 * scale}px; margin-right: ${2 * scale}px; width: ${10 * scale}px; height: ${10 * scale}px; border-radius: 50%; color: ${this.colours[n].text}; background: ${this.colours[n].colour}; font-weight: bold; font-size: 1.8em; text-align: center; border: 1px solid black; position: relative; float: left;">${n}</div>`;
// eslint-disable-next-line max-len
}).join('')}</div><div style="display: inline-block; padding-left: padding-right: 5px;">${(this.guesses[i] || [null, null, null, null, [null]]).slice(4, 5).map(n => {
if (typeof n[0] !== 'number') return `<div style="width: ${14 * scale}px; display: inline-block;"></div>`;
let out = '';
// eslint-disable-next-line max-len
out += Array.from({ length: n[0] }).map(t => `<div style="width: ${3 * scale}px; height: ${3 * scale}px; background: #E60000; vertical-align: middle; display: inline-block; border-radius: 50%; border: 0.5px solid black; text-align: center; margin-left: margin-right: ${2 * scale}px;"><div style="height: 40%; width: 40%; top: 30%; left: 30%; border-radius: 50%; border: none; background: ${Bot.AFD ? `#B3B3B3` : `#800000`}; position: relative;"></div></div>`).join('');
// eslint-disable-next-line max-len
out += Array.from({ length: n[1] }).map(t => `<div style="width: ${3 * scale}px; height: ${3 * scale}px; background: white; vertical-align: middle; display: inline-block; border-radius: 50%; border: 0.5px solid black; text-align: center; margin-left: margin-right: ${2 * scale}px;"><div style="height: 40%; width: 40%; top: 30%; left: 30%; border-radius: 50%; border: none; background: ${Bot.AFD ? `#800000` : `#B3B3B3`}; position: relative;"></div></div>`).join('');
// eslint-disable-next-line max-len
out += Array.from({ length: 4 - n[0] - n[1] }).map(t => `<div style="width: ${3 * scale}px; height: ${3 * scale}px; background: none; vertical-align: middle; display: inline-block; border-radius: 50%; border: none; text-align: center; margin-left: margin-right: ${2 * scale}px;"><div style="height: 40%; width: 40%; top: 30%; left: 30%; border-radius: 50%; border: 1px solid black; background: #4D4D4D; position: relative;"></div></div>`).join('');
return out;
}).join('%%')}</div>`;
}
// eslint-disable-next-line max-len
html += `</div>${player ? `<div style="border:1px solid;padding:20px;display:inline-block;vertical-align:top;"><form data-submitsend="/msgroom ${this.room},/botmsg ${Bot.status.nickName},${prefix}mastermind ${this.room} guess {guess}"><input type="text" name="guess" placeholder="Your guess!"/><br/><br/><center><input type="submit" value="Submit"></center></form></div>` : ''}</div>`;
return html;
}
sendPages (onlyPlayer) {
const list = onlyPlayer ? [] : JSON.parse(JSON.stringify(this.spectators));
list.unshift(this.player);
const spacer = () => {
if (list.length) {
// eslint-disable-next-line max-len
Bot.say(this.room, `/sendhtmlpage ${list[0]}, Mastermind + ${this.room} + ${this.player}, ${this.boardHTML(list.shift() === this.player)}`);
}
setTimeout(spacer, 500);
};
spacer();
return;
}
}
module.exports = Mastermind;
<file_sep>/commands/global/lbreset.js
module.exports = {
help: `Resets the leaderboard for the room. Requires #.`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
if (!Bot.rooms[room].lb) return Bot.say(room, 'This room doesn\'t have a Leaderboard!');
if (!Bot.rooms[room].resetLB) {
Bot.say(room, 'Are you sure you want to reset the leaderboard? If you are, use this again within 10 seconds.');
Bot.rooms[room].resetLB = true;
setTimeout(() => delete Bot.rooms[room].resetLB, 10000);
return;
}
Bot.log(JSON.stringify(Bot.rooms[room].lb.users));
Bot.log(`^ ${Bot.rooms[room].title} points were reset.`);
Bot.rooms[room].lb.users = {};
tools.updateLB(room);
return Bot.say(room, 'Points were reset!');
}
};
<file_sep>/data/PUZZLES/index.js
const protoDB = require('origindb')('data/PUZZLES/db'), DB = protoDB('teams');
const guildID = '816252178104320011';
const announcementChannel = client.channels.cache.get('816341849076793394');
const hintChannel = client.channels.cache.get('816335136035438622');
const logChannel = client.channels.cache.get('816335564894765109');
const parentChannel = client.channels.cache.get('816350143938428989');
const IDs = {
staff: '816252289953038336',
staffChannel: '816255459690020865'
};
module.exports = {
guildID: guildID,
live: true,
IDs: IDs,
hintChannel: hintChannel,
save: function () {
return protoDB.save();
},
log: function (input) {
let out;
if (typeof input === 'string') out = input;
else if (typeof input === 'function') out = input.toString();
else out = require('util').inspect(input);
return logChannel.send(`${out.substr(0, 1990)}`);
},
getPuzzle: function (puzzle) {
const puzzles = JSON.parse(fs.readFileSync('./data/PUZZLES/puzzles.json', 'utf8'));
puzzle = typeof puzzle === 'object' ? puzzle.id : toID(String(puzzle));
if (puzzle === 'constructor') return null;
return puzzles.find(pzz => pzz.id === puzzle || pzz.index === puzzle.toUpperCase() || pzz.aliases.includes(puzzle)) || false;
},
displayPuzzle: function (puzzle) {
puzzle = this.getPuzzle(puzzle);
if (!puzzle) return 'Something went wrong! (Unable to find puzzle)';
const Discord = require('discord.js'), embed = new Discord.MessageEmbed();
embed.setColor('#0099ff');
embed.setTitle(`Puzzle ${puzzle.index}: ${puzzle.title}`).addFields(puzzle.embedFields).setURL(puzzle.url);
if (puzzle.embedImage) embed.setImage(puzzle.embedImage);
return embed;
},
getTeam: function (context) {
if (typeof context === 'object' && context.role) {
return context;
} else if (typeof context === 'object' && context.roles && context.roles.cache) {
return Object.values(DB.object()).find(team => context.roles.cache.find(role => role.id === team.role));
} else if (typeof context === 'string' && /^\d+$/.test(toID(context))) {
return Object.values(DB.object()).find(team => team.role === toID(context) || team.channel === toID(context));
} else if (typeof context === 'string') {
return Object.values(DB.object()).find(team => team.name === context.trim()) ||
Object.values(DB.object()).find(team => team.id === toID(context));
} else return null;
},
allTeams: function () {
return DB.keys();
},
addTeam: function (message, name) {
name = name.trim();
if (this.getTeam(message, name)) return message.channel.send(`The specified team already exists.`);
const id = toID(name), channelName = name.toLowerCase().replace(/ /g, '-').replace(/[^a-z0-9-]/g, '');
if (id === 'constructor') return message.channel.send('...really?');
message.guild.roles.create({
data: {
name: name,
hoist: true
}
}).then(role => {
const team = {
members: [],
name: name,
id: id,
role: role.id,
puzzles: {},
unlocked: ['1', '2', '3', '4', '5', 'M'],
unsolved: ['1', '2', '3', '4', '5', 'M'],
hints: 0
};
['1', '2', '3', '4', '5', 'M'].forEach(lv => team.puzzles[lv] = 0);
if (!message.mentions.users.size) {
message.channel.send(`WARN: no users were mentioned. Team will be created, but role will have to be manually added.`);
}
const memProm = [];
for (const clientUser of message.mentions.users) {
const guildMember = message.guild.members.cache.get(clientUser[1].id);
memProm.push(new Promise((resolve, reject) => {
guildMember.roles.add(role).then(user => {
team.members.push(user.id);
resolve(clientUser.username || clientUser.name);
}).catch(e => {
Bot.log(e);
message.channel.send(e.message);
});
}));
}
Promise.all(memProm).then(mems => {
DB.set(id, team);
message.channel.send(`Successfully added ${role.name}!`);
message.guild.channels.create(channelName, {
type: 'text',
parent: parentChannel,
permissionOverwrites: [
{
id: guildID,
deny: ['VIEW_CHANNEL']
},
{
id: role.id,
allow: ['VIEW_CHANNEL', 'MANAGE_MESSAGES']
},
{
id: IDs.staff,
allow: ['VIEW_CHANNEL']
}
]
}).then(channel => {
channel.send(`Welcome to the UGO Puzzle Weekend!`);
channel.send(this.help(false));
this.log(`${team.name} has been registered!`);
DB.object()[id].channel = channel.id;
this.save();
});
}).catch(e => {
Bot.log(e);
message.channel.send(`Something went wrong! ID#1: (${e.message})`);
});
}).catch(e => {
Bot.log(e);
message.channel.send(`Something went wrong! ID#2: (${e.message})`);
});
},
addHints: function (team, amount, log) {
return new Promise((resolve, reject) => {
team = this.getTeam(team);
if (!team) return reject('Invalid team.');
if (team.hints + amount < 0) return reject(`Team only has ${team.hints} hints.`);
const teamDB = DB.object()[team.id];
teamDB.hints += amount;
this.save();
if (log) this.log(`${team.name} received ${amount} hint(s).`);
resolve(teamDB.hints);
});
},
massHints: function (amt) {
return Promise.all(Object.keys(DB.object()).map(team => this.addHints(team, amt, false)));
},
update: function (context) {
const inTeam = this.getTeam(context);
if (!inTeam) return null;
const team = DB.object()[inTeam.id];
team.unlocked = [];
const solved = Object.values(team.puzzles).filter(puzzle => puzzle).length;
for (let i = 1; i <= 5; i++) team.unlocked.push(String(i));
team.unlocked.push('M');
team.unsolved = team.unlocked.filter(puzzle => team.puzzles[puzzle] === 0);
this.save();
return true;
},
guess: function (team, puzzle, answer) {
team = this.getTeam(team);
puzzle = this.getPuzzle(puzzle);
return new Promise((resolve, reject) => {
if (!team || !puzzle) return reject('Unable to find the puzzle you meant.');
if (team.puzzles[puzzle.index]) return reject('You have already solved this puzzle!');
if (toID(answer) === toID(puzzle.solution)) {
DB.object()[team.id].puzzles[puzzle.index] = Date.now();
this.save();
this.update(team);
if (puzzle.index !== 'M') {
this.log(`:white_check_mark: ${team.name} completed Puzzle#${puzzle.index}: ${puzzle.title}.`);
} else {
announcementChannel.send(`<@&${team.role}> finished the metapuzzle! :D`);
this.log(`<@&${IDs.staff}> ${team.name} finished the metapuzzle yeet`);
}
if (!team.unsolved.length) {
this.log(`${team.name} completed all puzzles!`);
client.channels.cache.get(team.channel).send('Congratulations on finishing all puzzles!');
}
return resolve(true);
}
this.log(`:x: ${team.name} guessed [${toID(answer).toUpperCase()}] for ${puzzle.title}.`);
return resolve(false);
});
},
help: function (isStaff) {
const Discord = require('discord.js'), embed = new Discord.MessageEmbed();
// eslint-disable-next-line max-len
embed.setTitle('UGO Puzzle Weekend').setColor('#1F618D').addField('\u200b', `**${prefix}help** - Brings up this dialogue.\n**${prefix}puzzles** - Shows all the puzzles that you have unsolved; add 'all' to view all unlocked puzzles.\n**${prefix}puzzle (id / name)** - Views the specified puzzle.\n**${prefix}guess (puzzle), (answer)** - Makes a guess on the specified puzzle. Feel free to use multiple guesses, but no spamguessing, please!\n**${prefix}solved** - Displays a list of all unlocked puzzles and (if solved) their solutions.\n**${prefix}hints** - Displays the number of hints you have remaining.\n**${prefix}usehint (puzzle)** - Uses a hint on the specified puzzle; requires you to confirm.${isStaff ? '\n\n\n' : ''}`);
// eslint-disable-next-line max-len
if (isStaff) embed.addField('Staff Commands', `**${prefix}addteam (Team Name), @User1, @User2...** - Adds the given team to the puzzle hunt, and allots the mentioned users to the team.\n**${prefix}puzzlers** - Displays the puzzles solved by all teams, or the specified team.\n**${prefix}addhints (@Team), (amount)** - Gives the specified team (amount) hints. May be negative.\n**${prefix}deliverhints (amount)** - Adds (amount) hints to every team in the hunt. Use once a day to deliver the daily hint.\n**${prefix}allhints** - Displays the number of hints every team has.\n**${prefix}refundhint (@Team)** - Adds one hint to the given team; usually used to refund an accidental hint.`);
return embed;
}
};
<file_sep>/handlers/chat.js
module.exports = function (room, time, by, message) {
if (typeof Bot.jpcool[room] === 'object') Object.keys(Bot.jpcool[room]).forEach(user => Bot.jpcool[room][user][0]++);
if (toID(by) === toID(Bot.status.nickName)) return; // Botception
if (tools.hasPermission(by, 'none', room)) require('./autores.js').check(message, by, room);
if (!message.startsWith(prefix)) return;
if (message === `${prefix}eval 1`) return Bot.say(room, '1');
const args = message.substr(prefix.length).split(' ');
if (args[0].toLowerCase() === 'constructor') {
return Bot.say(room, `/me constructs a constrictor to constrict ${by.substr(1)}`);
}
const commandName = tools.commandAlias(args.shift().toLowerCase());
if (!commandName) return;
if (['eval', 'output'].includes(commandName)) {
if (!tools.hasPermission(toID(by), 'admin')) return Bot.pm(by, 'Access denied.');
(async () => {
try {
const output = eval(args.join(' '));
let outStr = output?.constructor.toString().includes('AysncFunction()') ? await output : output;
switch (typeof outStr) {
case 'object': outStr = commandName === 'eval' ? JSON.stringify(outStr) : util.inspect(outStr); break;
case 'function': outStr = outStr.toString(); break;
}
const postStr = String(outStr).replaceAll(config.pass, '***');
if (commandName === 'eval') {
Bot.say(room, postStr);
} else {
Bot.say(room, '!code ' + postStr);
}
} catch (e) {
Bot.log(e);
Bot.say(room, e.message);
}
})();
return;
}
return Bot.commandHandler(commandName, by, args, room);
};
<file_sep>/data/VR/TC7/steel.js
exports.steel = {
sp: ["Lucario-Mega", "Heatran", "", "Aegislash"],
s: ["", "Aggron-Mega", "Metagross-Mega"],
sm: [],
ap: ["Kartana", "Genesect", "Cobalion"],
a: ["Magnezone", "Celesteela", "Excadrill", "Steelix", "Aggron"],
am: ["Genesect", "Steelix-Mega"],
bp: [""],
b: ["Cobalion", "Klang", "Togedemaru"],
bm: ["Mawile-Mega", "Magearna", "Durant"],
cp: ["Bronzong"],
c: ["Empoleon", "Dugtrio-Alola"],
cm: ["Stakataka", "Probopass"],
d: ["Doublade", "Skarmory"],
e: [],
unt: ["Magneton", "", "Forretress"],
bans: []
};
<file_sep>/commands/global/hplm.js
module.exports = {
cooldown: 5000,
noDisplay: true,
help: `Broadcasts HPL matches.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
// eslint-disable-next-line max-len
if (!tools.hasPermission(by, 'coder') && !tools.hasPermission(by, 'beta', 'hindi') && !['crowmusic', 'premmalhotra', 'rajshoot', 'shivamo', 'thedarkrising'].includes(toID(by))) return Bot.pm(by, 'Access denied.');
if (!room.startsWith('battle-')) return Bot.pm(by, "Only for battlerooms.");
if (Bot.hindi?.hplStored?.[room]) {
return Bot.say(room, `${Bot.hindi.hplStored[room]} ne already ping kiya tha, lekin shukriya!`);
}
// eslint-disable-next-line max-len
client.channels.cache.get("856437495322902538").send(`<@&854676701208641556> ${Bot.rooms[room].title}: https://play.pokemonshowdown.com/${room}`).then(() => {
if (!Bot.rooms.hindi?.hplStored) Bot.rooms.hindi.hplStored = {};
Bot.rooms.hindi.hplStored[room] = by.substr(1);
Bot.say(room, 'Pinged; shukriya!');
}).catch(Bot.log);
}
};
<file_sep>/handlers/ticker.js
module.exports = function (Bot) {
// This will run every 20 seconds. Keep this code as efficient as possible.
// Auto-ladder for the Metronome ladder
if (config.autoLadder) {
const games = Object.values(BattleAI.games);
if (games.filter(game => game.tier === '[Gen 8] Metronome Battle').length < 5) {
Bot.say('botdevelopment', `/utm ${Bot.teams['gen8metronomebattle'].random()}`);
Bot.say('botdevelopment', '/search gen8metronomebattle');
}
}
// Pulling battles for 2v2
/*
if (Bot.rooms['2v2']) {
Bot.say('', '/cmd roomlist gen92v2doubles');
}
*/
// Disabled for now
};
<file_sep>/handlers/discord_reacts.js
exports.reactToReacts = (reaction, user) => {
if (reaction.message.channel.id === '952343311182602290') {
// First is #code-2, second is actual
if (reaction._emoji.name === '✅' && reaction.count === 2) {
// Checked!
const message = reaction.message;
const matches = message.content.match(/(?:\*\*.*?\*\*|https:\/\/replay.pokemonshowdown.com\/[a-z0-9A-Z-]*)/g);
if (!matches || matches.length !== 3) return message.channel.send('Unable to find challenge/user/replay');
const [challenge, challenger, replay] = matches.map(str => str.replace(/(?:^\*\*|\*\*$)/g, ''));
const difficulty = Bot.DB('trickhouse').get(toID(challenge));
const id = Date.now();
// eslint-disable-next-line max-len
const html = `<form data-submitsend="/w ${Bot.status.nickName},${prefix}trickhouse {challenger}, {difficulty}, {replay}, ${id}">Challenge detected for user <input type="text" value="${challenger}" name="challenger"/> of difficulty <select name="difficulty"><option name="difficulty" value="1"${difficulty === 1 ? 'selected' : ''}>Easy</option><option name="difficulty" value="2"${difficulty === 2 ? 'selected' : ''}>Medium</option><option name="difficulty" value="3"${difficulty === 3 ? 'selected' : ''}>Hard</option></select> (the ${challenge} Challenge). Challenge replay: <input type="text" placeholder="Paste replay link here" name="replay" value="${replay}" style="width:400px"/><br/><button>Submit!</button></form>`;
const Room = Bot.rooms.trickhouse;
if (!Room) return message.channel.send(`Wait I don't seem to be in the room oops`);
if (!Room.vers) Room.vers = {};
Room.vers[id] = { challenge, challenger, replay, html };
Bot.say('trickhouse', `/addrankuhtml %, trickhouse-${toID(challenge)}-${toID(challenger)}-${id}, ${html}`);
}
}
};
exports.loadMessages = async client => {
await client.channels.cache.get('766946356018413588').messages.fetch();
await client.channels.cache.get('952343311182602290').messages.fetch();
};
<file_sep>/pmcommands/stop.js
module.exports = {
help: `Stops a running timer.`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
if (!Bot.pmtimers) return Bot.pm(by, `You don't have any ongoing timers.`);
if (Bot.pmtimers[toID(by)]) {
clearTimeout(Bot.pmtimers[toID(by)]);
delete Bot.pmtimers[toID(by)];
return Bot.pm(by, 'Stopped timer!');
} else return Bot.pm(by, `You don't have any ongoing timers.`);
}
};
<file_sep>/commands/global/tour.js
module.exports = {
cooldown: 10,
help: `The PS /tour command. Use \`\`/tour help\`\` for help.`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, args.length ? '/tour ' + args.join(' ') : 'UwU');
}
};
<file_sep>/commands/pokemongo/weatheris.js
module.exports = {
cooldown: 0,
help: `Changes a raid's weather.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
const user = toID(by);
const raids = Bot.rooms[room].raids || {};
if (!Object.keys(raids).length) return Bot.roomReply(room, by, "No raids are active, whoops");
const host = user;
if (!raids.hasOwnProperty(host)) return Bot.roomReply(room, by, `B-but you're not hosting?`);
const raid = raids[host];
const weathers = {
"sunny": ["fire", "grass", "ground"],
"clear": ["fire", "grass", "ground"],
"partlycloudy": ["normal", "rock"],
"cloudy": ["fairy", "fighting", "poison"],
"rain": ["water", "electric", "bug"],
"rainy": ["water", "electric", "bug"],
"snow": ["ice", "steel"],
"fog": ["dark", "ghost"],
"windy": ["dragon", "flying", "psychic"],
"unknown": []
};
const weather = toID(args.join(''));
if (!weathers.hasOwnProperty(weather)) {
// eslint-disable-next-line max-len
return Bot.roomReply(room, by, `Didn't recognize that weather! The only ones I recognize are: ${tools.listify(Object.keys(weathers).slice(0, -1))}`);
}
raid.weather = weather;
raid.wb = data.pokedex[raid.mon].types.some(t => weathers[raid.weather].includes(toID(t)));
Bot.say(room, `${by.substr(1)}'s raid weather is now ${args.join(' ')}`);
raid.HTML();
}
};
<file_sep>/commands/global/license.js
module.exports = {
cooldown: 1,
// eslint-disable-next-line max-len
help: `Adds / removes a license to / from the given user. Warning: Using this command prevents future changes to JPs without a license.`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args.length) return Bot.pm(by, unxa);
if (!Bot.rooms[room].shop) Bot.rooms[room].shop = {};
if (!Bot.rooms[room].shop.jpl) Bot.rooms[room].shop.jpl = [];
const name = args.join(' ');
if (Bot.rooms[room].shop.jpl.includes(toID(name))) {
Bot.rooms[room].shop.jpl.remove(toID(name));
Bot.log(by.substr(1) + ' delicensed ' + name + ' in ' + Bot.rooms[room].title);
tools.updateShops(room);
if (Bot.rooms[room].shop.channel) {
client.channels.cache.get(Bot.rooms[room].shop.channel).send(` ${name} has been delicensed for a joinphrase.`);
}
return Bot.say(room, `${name} has been delicensed for a joinphrase.`);
}
Bot.rooms[room].shop.jpl.push(toID(name));
Bot.log(by.substr(1) + ' licensed ' + name + ' in ' + Bot.rooms[room].title);
tools.updateShops();
if (Bot.rooms[room].shop.channel) {
client.channels.cache.get(Bot.rooms[room].shop.channel).send(` ${name} has been licensed for a joinphrase.`);
}
return Bot.say(room, ` ${name} has been licensed for a joinphrase.`);
}
};
<file_sep>/README.md
# PartBot
Base code for PartBot, a Bot on Pokémon Showdown.
Features:
At this point, there's way, way too many to list. Honestly just go through the code to find out.
### Setup
1. Clone the Git repository, or download the project and unzip it.
1. Open `config.js`. Enter the Bot prefix, Bot username, Bot password, Bot avatar, Bot status, Bot owner, and an array of rooms you'd like the Bot to join. Scroll down and add the IDs of the users that you would like to set in their respective ranks. For more details on ranks, read below.
1. Open your Terminal and enter the following:
```
npm install
npm run update-data
node bot.js
```
If all goes well, you should get a prompt notifying you of your Bot having connected.
#### Requirements
Node.js (> Node 14.0.0)
### Auth
Rank | Permissions
-----|------------
Locked | Limited access to help commands.
None | Standard access.
Gamma | Hangman and broadcasting access.
Beta | Moderation, Tour, and Game access.
Alpha | Control and Edit access.
Coder | Code, Maintainence access.
Admin | Complete access.
Auth | Rank
-----|-----
\+ | Gamma
\% | Beta
\*, @, #, &, ~ | Alpha (~ is still supported for sideservers)
For room-specific authority, edit the ./data/DATA/roomauth.json file, and add the auth as a property of the room key (it already has an example).
### Structure
PartBot has the following structure:
1. `client.js` is responsible for handling the connection between the Bot and the server. You will almost never be needed to edit this.
2. `bot.js` is the main file. It contains references to all the other files and initiates the Bot. It also contains the PM handler.
3. `handlers/chat.js` handles messages sent in chat, and messages that start with the prefix are redirected to the command handler, whose code can be found in `commands.js`.
4. `handlers/discord.js` contains the Discord command handler.
5. `handlers/autores.js` and `discord_chat.js` handle the PS and Discord autores, respectively.
6. `global.js` instantiates all global variables, including data.
7. `handlers/battle.js` handles the battle interface, `handlers/router.js` handles the website, `handlers/schedule.js` has scheduled daily functions, `handlers/ticker.js` handles the internal ticker (a function which runs periodically every 20 seconds), `handlers/tours.js` handles tournament-related stuff.
8. Commands can be found in `commands/ROOM/COMMAND.js`, with ROOM being 'global' for global commands. PM commands, similarly, are all in `pmcommands`.
9. `pages` contains most of the HTML-related templates and pages for the website, while `public` files can be accessed from anywhere through `${websiteLink}/public/filepath`.
10. The `data` folder contains all the relevant data files required to run the Bot. It also contains the `tools.js` and `hotpatch.js` files, which are used to expose the utilities and hotpatching mechanisms.
### Globals
PartBot's code has a variety of global variables, all of which can be found from global.js. Commonly used ones include:
1. ``toID``: The single most-used function in PartBot's code. Coverts a string input to its ID. (This was formerly known as toId, feel free to convert it to toID wherever you see it)
1. ``unxa``: "Unexpected number of arguments."
1. ``tools``: A global object with various useful functions. Go through ``./data/tools.js`` to view / edit them.
1. ``data``: A global object that stores most of the data (Pokedex, moves, etc). Check the requires in ``./globals.js`` to view the individual sources, which are mostly in ``./data/DATA``.
1. ``GAMES``: PartBot's Games module. You can find most of PartBot's games here; the module is in `data/GAMES`.
1. ``Bot``: The PS client. The class is defined in ``client.js``, but the instance is global. Primary functions include ``Bot.say(roomid, text)`` and ``Bot.pm(userid, text)``. State is mostly stored under various keys in the main object, and room data can be found in ``Bot.rooms``. Most games are assigned to the ``Bot.rooms[roomid]`` object.
### Discord Setup
Once you've set up the configuration file, there are still a couple steps left to set up Discord. If you have ``token`` set to false, ignore these steps.
1. Open `config.js` and replace the string ``'ADMIN_ID'`` with your Discord ID.
(Yeah, that was it)
#### Quick Help:
- How do I get the token for my Bot?
First, open the [Discord Developer Portal](https://discord.com/developers). If you haven't already done so, create an Application and set it up. After converting the application to a Bot, go to the Bot section and copy your token. This token grants access to your application, so keep it private.
- How do I get my Discord ID?
Go to Discord settings and enable Developer Mode. Once enabled, right click your name and copy the ID.
- How do I invite my Bot to a server?
You can only invite the Bot to servers in which you have the ``Manage Server`` permission. Open your application on the Discord Developer Portal, and go to OAuth2. In Scopes, select Bot, and scroll down to select the relevant permissions. After this, simply visit the link that pops up below Scopes. This link may be shared and used multiple times.
### Shop / Leaderboard
PartBot now supports separate leaderboards and shops. Even better, leaderboards can have any number of unique currencies.
Documentation for these will come soon. :sweat_smile:
#### To-do:
- [ ] Add moderation / promotion commands.
- [ ] Add CONTRIBUTING.md.
- [ ] Add proper website navigation.
- [ ] Do the stuff marked to-do #smort
### Credits:
PartMan - Lead Developer
Ecuacion - client.js base
Many thanks to the numerous people who helped me start out with this years ago.
<file_sep>/pmcommands/reload.js
module.exports = {
help: `Reloads the cache for a PM command. Syntax: ${prefix}reload (command)`,
permissions: 'coder',
commandFunction: function (Bot, by, args, client) {
const commandName = tools.pmCommandAlias(args.join(''));
fs.readdir('./pmcommands', (err, files) => {
if (err) {
Bot.pm(by, e.message);
return Bot.log(e);
}
if (!files.includes(commandName + '.js')) return Bot.pm(by, `It doesn't look like that command exists...`);
delete require.cache[require.resolve(`./${commandName}.js`)];
Bot.log(by.substr(1) + ' reloaded the ' + commandName + ' command.');
return Bot.pm(by, 'The ' + commandName + ' command has been reloaded.');
});
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/o.js
module.exports = {
cooldown: 10000,
help: `No, you.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `\\(o_o)/`);
}
};
<file_sep>/pmcommands/ship.js
module.exports = {
help: `Ships!`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
if (!args.length) return Bot.pm(by, unxa);
const cargs = args.join(' ').split(',').map(term => term.trim());
if (cargs.length < 1 || cargs.length > 2) return Bot.pm(by, unxa);
if (!cargs[1]) cargs.push(by.substr(1));
const terms = Array.from(cargs);
cargs.sort();
const comp = require('crypto')
.createHash('md5')
.update(toID(cargs[0]) + '&' + toID(cargs[1]), 'utf8')
.digest('hex')
.split('')
.map(letter => tools.scrabblify(letter) ** 13)
.reduce((a, b) => a + b) % 101;
return Bot.pm(by, `I do declare that ${terms[0]} and ${terms[1]} are ${comp}% compatible!`);
}
};
<file_sep>/pmcommands/leaderboard.js
module.exports = {
help: `Displays the leaderboard for the given room. Syntax: ${prefix}leaderboard (room), (users to display [optional])`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
if (!args.length) {
args = Object.keys(Bot.rooms).filter(room => Bot.rooms[room].users.find(u => toID(u) === toID(by)) && Bot.rooms[room].lb);
if (args.length !== 1) return Bot.pm(by, 'Which room?');
}
const cargs = args.join('').split(',');
const room = tools.getRoom(cargs.shift());
if (!room) return Bot.pm(by, 'Which room?');
if (!Bot.rooms[room]) return Bot.pm(by, "I'm not in that room! (does it even exist?)");
const lb = Bot.rooms[room].lb;
if (!lb) return Bot.pm(by, 'Nope, no leaderboard there.');
const sort = row => row.reduce((a, b, i) => a + (i ? b / 100000 ** i : 0), 0);
const data = Object.keys(lb.users).map(user => [lb.users[user].name, ...lb.users[user].points]);
if (!data.length) return Bot.pm(by, "Empty board. o.o");
// eslint-disable-next-line max-len
const html = tools.board(data, ['Name', ...lb.points.map(p => p[2])], sort, ['40px', '160px', ...Array.from({ length: lb.points.length }).map(t => Math.floor(150 / lb.points.length) + 'px')], Bot.rooms[room]?.template || 'orange', null, parseInt(toID(cargs.join(''))) || 10, 'Rank', true);
if (typeof html !== 'string') return Bot.pm(by, 'Something went wrong.');
return Bot.sendHTML(by, '<center>' + html + '</center>');
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/vote.js
module.exports = {
cooldown: 10,
help: `Allows you to vote / change your vote for an ongoing poll. Syntax: ${prefix}vote (option)`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args[0]) return Bot.say(room, unxa);
if (args[0].toLowerCase() === 'options') return Bot.say(room, 'The options for this poll are ' + tools.listify(typelist.map(type => type.charAt(0).toUpperCase() + type.substr(1)).sort()) + '.');
const name = toID(by);
const vType = toID(args.join(''));
if (!typelist.includes(vType)) return Bot.say(room, 'Invalid vote option.');
const pollRoom = room;
if (!pollObject[pollRoom] || !pollObject[pollRoom].active) return Bot.say(room, 'No polls are currently active in this room.');
if (pollObject[pollRoom].votes[name]) {
const oldType = pollObject[pollRoom].votes[name];
pollObject[pollRoom].votes[name] = vType;
if (oldType === vType) return Bot.say(room, 'You have already voted for ' + vType.charAt(0).toUpperCase() + vType.substr(1) + '!');
} else pollObject[pollRoom].votes[name] = vType;
Bot.say(room, 'Your vote has been cast!');
}
};
<file_sep>/commands/global/checkword.js
module.exports = {
cooldown: 0,
help: `Checks whether a given word is Scrabble-legal. Syntax: \`\`${prefix}checkword word(, dict, mod)\`\``,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
const WORDS = require('../../data/WORDS/index.js');
const [word, dict, mod] = args.join('').split(',');
let memeOverride = false;
if (room === 'boardgames' && toID(word) === 'plisaweeb') memeOverride = true;
const text = `${toID(word).toUpperCase()} is ${memeOverride || WORDS.checkWord(word, dict, mod) ? '' : 'not '} a Scrabble-legal word.`;
if (tools.hasPermission(by, 'gamma', room)) Bot.say(room, text);
else Bot.roomReply(room, by, text);
}
};
<file_sep>/commands/pokemongo/hundos.js
module.exports = {
cooldown: 0,
help: `Sets your PoGo raid list.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client, isPM) {
const cargs = args.join(' ').split(',');
let [mon, ...lv] = cargs;
mon = toID(mon);
if (!lv.length) lv = ['20', '25'];
lv = lv.map(t => parseFloat(t.replace(/[^0-9\.]/g, ''))).slice(0, 2);
if (lv.find(n => n > 51 || n < 1 || 2 * n % 1)) {
return Bot.roomReply(room, by, `Uhh why do you want to look at such a high level`);
}
mon = tools.queryGO(mon);
if (mon?.type !== 'pokemon') {
return Bot.roomReply(room, by, `Didn't find that as a valid Pokémon; I'm probably just bad.`);
}
mon = mon.info;
const divs = [[10, 10, 10], [15, 15, 15]];
// eslint-disable-next-line max-len
const output = `${mon.name} can have a CP of ${divs.map(ivs => tools.getCP(mon.name, lv[0], ivs)).join('-')} at Lv${lv[0]}${lv[1] ? ` (${divs.map(ivs => tools.getCP(mon.name, lv[1], ivs)).join('-')} at Lv${lv[1]})` : ''}, and can${mon.shiny ? '' : "not"} be shiny.`;
if (isPM) return Bot.pm(by, output);
else if (tools.hasPermission(by, 'gamma', room)) return Bot.say(room, output);
else Bot.roomReply(room, by, output);
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/poll.js
module.exports = {
cooldown: 1000,
help: `Creates a Tournament Poll with the given options. Syntax: ${prefix}poll (time (in minutes)) (autostart / official (optional))`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args[0]) return Bot.say(room, unxa);
const pollRoom = room;
if (args[0].toLowerCase() === 'status' || args[0].toLowerCase() === 'show' || args[0].toLowerCase() === 'view' || args[0].toLowerCase() === 'display') {
if (!pollObject[pollRoom].active) return Bot.say(room, 'No polls are currently active.');
const outArr = Object.keys(pollObject[pollRoom].votes).filter(name => name.toLowerCase() === name).map(name => pollObject[pollRoom].votes[name]).map(name => name.charAt(0) + name.substr(1)).sort();
let curWin = tools.modeArray(outArr).map(type => type.charAt(0).toUpperCase() + type.substr(1)).sort();
if (!curWin[0]) curWin = false;
const timeRem = pollObject[pollRoom].endTime - Date.now();
return Bot.say(room, 'The poll will end in ' + tools.toHumanTime(timeRem) + '. Currently, ' + (curWin ? tools.listify(curWin) + ' ' + (curWin.length == 1 ? 'is' : 'are') + ' in the lead.' : 'no votes have been cast.'));
}
if (args[0].toLowerCase() === 'cancel') {
if (!pollObject[pollRoom].active) return Bot.say(room, "No polls are currently active.");
clearTimeout(pollSetTimer);
pollObject[pollRoom].active = false;
pollObject[pollRoom].votes = {};
pollObject[pollRoom].autostart = false;
pollObject[pollRoom].endTime = 0;
return Bot.say(room, 'The poll has been cancelled.');
}
if (args[0].toLowerCase() === 'end') {
if (!pollObject[pollRoom].active) return Bot.say(room, "No polls are currently active.");
clearTimeout(pollSetTimer);
return startPoll(pollRoom);
}
if (pollObject[pollRoom].active) return Bot.say(room, 'A poll is already active.');
if (pollObject[pollRoom]) {
pollObject[pollRoom] = {
votes: {},
active: true,
autostart: false,
official: false,
endTime: 0
};
}
let ttime = parseFloat(args[0].replace(/[^0-9]/g, ''));
if (args[1] && ['as', 'autostart'].includes(toID(args[1]))) pollObject[pollRoom].autostart = true;
if (isNaN(ttime)) return Bot.say(room, 'Invalid time.');
if (ttime > 20 || ttime < 0.5) return Bot.say(room, 'Given time does not fall in a valid range.');
ttime *= 60000;
typelist.forEach(type => {
pollObject[pollRoom].votes[type.toUpperCase()] = type;
});
function startPoll (pollRoom) {
if (!pollObject[pollRoom]) return Bot.say(room, 'Something went wrong.');
const finalType = tools.modeArray(Object.values(pollObject[pollRoom].votes))[Math.floor(Math.random() * tools.modeArray(Object.values(pollObject[pollRoom].votes)).length)];
if (!typelist.includes(finalType)) return Bot.say(room, 'Error: Type not found.');
Bot.say(room, 'The poll has ended!');
if (!pollObject[pollRoom].autostart) {
if (Object.keys(pollObject[pollRoom].votes).length === 18) {
pollObject[pollRoom].active = false;
pollObject[pollRoom].votes = {};
pollObject[pollRoom].endTime = 0;
return Bot.say(room, 'No votes were cast, so I chose ' + finalType.charAt(0).toUpperCase() + finalType.substr(1) + '!');
}
pollObject[pollRoom].active = false;
pollObject[pollRoom].votes = {};
pollObject[pollRoom].endTime = 0;
return Bot.say(room, 'The voted type was ' + finalType.charAt(0).toUpperCase() + finalType.substr(1) + '!');
}
function staggerSay (stuff) {
Bot.say(room, stuff);
}
Bot.say(room, '/tour create 1v1, rr, , 2');
Bot.say(room, require('../../data/TOURS/CODES/TC/' + finalType + '.js')[finalType]);
Bot.say(room, '$settype ' + finalType);
if (pollObject[pollRoom].official) setTimeout(staggerSay, 1000, '$official');
pollObject[pollRoom].active = false;
pollObject[pollRoom].votes = {};
pollObject[pollRoom].autostart = false;
pollObject[pollRoom].endTime = 0;
const tourArr = JSON.parse(fs.readFileSync('./data/DATA/tourrecords.json', 'utf8'));
tourArr.push({ official: false, type: finalType, starter: toID(by), time: Date.now() });
fs.writeFileSync('./data/DATA/tourrecords.json', JSON.stringify(tourArr));
client.channels.get('549432010322477056').send(`Type: ${finalType.charAt(0).toUpperCase() + finalType.slice(1)} Tour started!`);
}
global.pollSetTimer = setTimeout(startPoll, ttime, pollRoom);
pollObject[pollRoom].endTime = Date.now() + ttime;
Bot.say(room, '/wall Voting for the next Tournament is now open! Use ' + prefix + 'vote (type) to vote!');
pollSetTimer;
}
};
<file_sep>/commands/global/viewjoinphrases.js
module.exports = {
cooldown: 1000,
help: `Displays a list of all joinphrases in the room. Syntax: ${prefix}viewjoinphrases`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
if (!Bot.jps[room] || !Object.keys(Bot.jps[room]).length) {
return Bot.say(room, `It doesn't look ike this room has any joinphrases...`);
}
const info = Object.entries(Bot.jps[room]).map(([name, jp]) => [tools.colourize(name), tools.escapeHTML(jp)]);
const html = `<table>${info.map(row => `<tr>${row.map(term => `<td>${term}</td>`).join('')}</tr>`).join('')}</table>`;
return Bot.sendHTML(by, html);
}
};
<file_sep>/commands/boardgames/apl.js
module.exports = {
cooldown: 100,
help: `Whitelist... list?`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
const html = tools.listify(Bot.rooms[room]?.auth?.gamma.map(name => tools.colourize(name)));
if (tools.hasPermission(by, 'gamma', room)) Bot.say(room, `/adduhtml APL,${html}`);
else Bot.say(room, `/sendprivatehtmlbox ${by}, ${html}`);
}
};
<file_sep>/pmcommands/git.js
module.exports = {
help: `Displays PartBot's GitHub repository.`,
permissions: 'locked',
commandFunction: function (Bot, by, args, client) {
Bot.pm(by, `https://github.com/PartMan7/PartBot`);
}
};
<file_sep>/commands/global/omintro.js
module.exports = {
cooldown: 100000,
help: `Displays the roomintro for the 1v1 OMs.`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
// eslint-disable-next-line max-len
Bot.say(room, `!htmlbox <center><img src="https://i.ibb.co/x5S1mDT/DRUD.png" usemap="#image-map" height="195" width="417"><map name="image-map"><area target="" alt="Introduction" title="Introduction" name="send" value="INTRO" coords="37,23,170,50" shape="rect"><area target="" alt="Tiers List" title="Tiers List" name="send" value="TIERS" coords="30,154,114,191" shape="rect"><area target="" alt="Smogon" title="Smogon" href="https://www.smogon.com/forums/threads/1v1-oms.3648454/" coords="127,154,249,190" shape="rect"><area target="" alt="Roomauth" title="Roomauth" name="send" value="ROOMAUTH" coords="264,155,390,189" shape="rect"></map></center>`);
}
};
<file_sep>/commands/hindi/hpls.js
module.exports = {
cooldown: 1,
help: `HPL schedule`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
return Bot.roomReply(room, by, `Disabled.`);
try {
const cur = new Date(new Date().toLocaleString('GMT', { timeZone: 'Asia/Kolkata' })).getTime();
delete require.cache[require.resolve('../../data/DATA/scheduled.json')];
const { teamValues, schedule } = require('../../data/DATA/scheduled.json');
const sorter = (a, b) => {
if (a.time < cur) a.time += 7 * 24 * 60 * 60 * 1000;
if (b.time < cur) b.time += 7 * 24 * 60 * 60 * 1000;
return a.time - b.time;
};
if (!schedule.length) return Bot.roomReply(room, by, 'There are no scheduled matches.');
// eslint-disable-next-line max-len
const html = `<hr/><center style="max-height:270px;overflow-y:scroll;"><table style="border:1px;border-style:collapse;">${schedule.sort(sorter).slice(0, 25).map(match => `<tr style="height:36px;"><td style="font-size:0.8em;">${match.match.replace(/\s*\([^)]*\)\s*/g, '')}</td><td style="text-align:center;width:180px;">${tools.colourize(match.players[0])}</td><td style="width:36px;background-color:${teamValues[toID(match.teams[0])].color};text-align:center;"><img src="${teamValues[toID(match.teams[0])].logo}" height="30" width="30" style="vertical-align:middle;"/></td><td style="width:36px;background-color:${teamValues[toID(match.teams[1])].color};text-align:center;"><img src="${teamValues[toID(match.teams[1])].logo}" height="30" width="30" style="vertical-align:middle;"/></td><td style="text-align:center;width:180px;">${tools.colourize(match.players[1])}</td><td>${match.schedule}</td></tr>`).join('')}</table></center><hr/>`;
if (tools.hasPermission(by, 'gamma', room)) Bot.say(room, `/adduhtml HPLSCHEDULE, ${html}`);
else Bot.sendHTML(by, html);
} catch (e) {
if (tools.hasPermission(by, 'gamma', room)) Bot.say(room, `Abhi to koi scheduled nahi hai.`);
else Bot.pm(by, `Abhi to koi scheduled nahi hai.`);
}
}
};
<file_sep>/pmcommands/pogoregisteras.js
module.exports = {
noDisplay: true,
help: `Registers someone on PoGo`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
const room = 'pokemongo';
if (!Bot.rooms[room]?.users.some(u => toID(u) === toID(by))) return Bot.pm(by, '<<pokemongo>>');
if (!tools.hasPermission(by, 'gamma', room)) return Bot.pm(by, `OOH LOOK A WILD PANSEAR`);
if (!args.length) return Bot.roomReply(room, by, `You kinda need to type in the name first...`);
let isBy = ' ';
args = args.join(' ').replace(/^[^,]*,/, m => {
isBy += m.slice(0, -1).trim();
return '';
}).split(' ');
return Bot.commandHandler('setuser', isBy, args, room, by);
}
};
<file_sep>/commands/global/addjoinphrase.js
module.exports = {
cooldown: 10,
help: `Adds a joinphrase. Syntax: ${prefix}addjoinphrase (user), (joinphrase)`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
if (!Bot.jps[room]) {
Bot.jps[room] = {};
fs.writeFile(`./data/JPS/${room}.json`, '{}', e => {
if (e) return console.log(e);
});
}
const cargs = args.join(' ').split(/,/);
if (!cargs[1]) return Bot.say(room, unxa);
const name = toID(cargs.shift());
if (Bot.rooms[room].shop?.jpl?.length && !Bot.rooms[room].shop.jpl.includes(name)) {
return Bot.say(room, `They don't have a license, though. That's illegal. :(`);
}
if (Bot.jps[room][name]) return Bot.say(room, `That user already has a JP! Use ${prefix}editjoinphrase instead.`);
let jp = cargs.join(',').trim();
if (/(?:kick|punt)s? .*\bSnom\b/i.test(jp)) return Bot.say(room, `That's not acceptable.`);
if (/^\/[^\/]/.test(jp) && !/^\/mee? /.test(jp)) jp = '/' + jp;
if (/^!/.test(jp) && !/^!n?da?(?:ta?|s) /.test(jp)) jp = ' ' + jp;
Bot.jps[room][name] = jp;
fs.writeFile(`./data/JPS/${room}.json`, JSON.stringify(Bot.jps[room], null, 2), e => {
if (e) return console.log(e);
Bot.say(room, 'Joinphrase added!');
});
}
};
<file_sep>/bot.js
'use strict';
const http = require('http');
const SDClient = require('./client.js');
global.Discord = require('discord.js');
const express = require('express');
require('./global.js');
const options = {
nickName: config.nickName,
pass: config.pass,
avatar: config.avatar ?? null,
status: config.status ?? null,
autoJoin: config.autoJoin,
debug: config.debug
};
global.app = express();
global.Bot = new SDClient(options);
global.client = new Discord.Client({ partials: ['MESSAGE', 'REACTION'], autoReconnect: true });
Bot.connect();
const minor = require('./handlers/minorhandler');
minor.initialize();
Object.keys(minor).forEach(key => Bot.on(key, minor[key]));
Bot.on('battle', (...args) => require('./handlers/battle.js').handler(...args));
Bot.chatHandler = require('./handlers/chat.js');
Bot.pmHandler = require('./handlers/pmhandler.js');
Bot.pageHandler = require('./handlers/pages.js');
Bot.processHandler = require('./handlers/processhandler.js').init(Bot);
Bot.on('chat', (room, time, by, message) => Bot.chatHandler(room, time, by, message));
Bot.on('pm', (by, message) => Bot.pmHandler(by, message));
Bot.router = require('./handlers/router.js');
Bot.ticker = setInterval(() => require('./handlers/ticker.js')(Bot), 55 * 1000);
Bot.schedule = require('./handlers/schedule.js')();
client.on('message', (...args) => require('./handlers/discord.js').handler(...args));
client.login(config.token, err => console.log(err));
client.on('ready', () => {
console.log('Connected to Discord');
client.user.setActivity('Type Challenge: Ghost!');
const { loadMessages, reactToReacts } = require('./handlers/discord_reacts.js');
loadMessages(client).then(() => client.on('messageReactionAdd', (...args) => reactToReacts(...args)));
});
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get(/.*/, (req, res) => Bot.router.get(req, res));
app.post(/.*/, (req, res) => Bot.router.post(req, res));
const server = app.listen(config.webPort, () => console.log(`The website\'s up at ${websiteLink}!`));
<file_sep>/handlers/database.js
const mongoose = require('mongoose');
mongoose.connect(config.mongoURL, () => console.log('Connected to MongoDB'));
const seenSchema = new mongoose.Schema({
_id: { type: String, required: true },
time: { type: Date, required: true }
});
const altSchema = new mongoose.Schema({
_id: { type: String, required: true },
alts: { type: [{ _id: String }], required: true }
});
const seen = mongoose.model('seen', seenSchema);
const alts = mongoose.model('alt', altSchema);
const seenQueue = [];
const altQueue = [];
function see (user, time) {
user = toID(user);
return new Promise((resolve, reject) => {
function enqueue () {
return seen.findOneAndUpdate({ _id: user }, { _id: user, time: time }, { new: true, upsert: true }).then(res => {
seenQueue.shift();
seenQueue[0]?.();
resolve(res);
});
}
seenQueue.push(enqueue);
if (seenQueue.length === 1) enqueue();
});
}
function alt (A, B) {
[A, B] = [toID(A), toID(B)];
return new Promise((resolve, reject) => {
function enqueue () {
return Promise.all([
alts.findOneAndUpdate({ _id: A }, { _id: A, $addToSet: { alts: { _id: B } } }, { new: true, upsert: true }),
alts.findOneAndUpdate({ _id: B }, { _id: B, $addToSet: { alts: { _id: A } } }, { new: true, upsert: true })
]).then(res => {
altQueue.shift();
altQueue[0]?.();
resolve(res);
});
}
altQueue.push(enqueue);
if (altQueue.length === 1) enqueue();
});
}
async function lastSeen (user) {
user = toID(user);
const temp = await seen.findOne({ _id: user });
return temp?.time || false;
}
async function getAlts (user) {
user = toID(user);
const temp = await alts.findOne({ _id: user }).lean();
return temp?.alts.map(term => term._id) || [];
}
module.exports = {
see,
alt,
lastSeen,
getAlts
};
<file_sep>/commands/global/leaderboard.js
// TODO: Refactor
module.exports = {
cooldown: 10,
help: `Displays the Leaderboard for the room.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
const lb = Bot.rooms[room].lb, shop = Bot.rooms[room].shop;
if (!lb) return Bot.pm(by, 'Nope, no leaderboard here.');
if (room === 'hindi' && !tools.hasPermission(by, 'gamma', room)) {
return Bot.roomReply(room, by, `Sorry, isko disable kiya hai; PMs mei \`\`${prefix}lb hindi, 50\`\` try kar lo!`);
}
const sort = row => row.reduce((a, b, i) => a + (i ? b / 100000 ** i : 0), 0);
const info = Object.keys(lb.users).map(user => [lb.users[user].name, ...lb.users[user].points]);
if (!info.length) return Bot.say(room, "Empty board. o.o");
// eslint-disable-next-line max-len
const boardArgs = [info, ['Name', ...lb.points.map(p => p[2])], sort, ['40px', '160px', ...Array.from({ length: lb.points.length }).map(t => Math.floor(150 / lb.points.length) + 'px')], Bot.rooms[room].template || 'orange', null, parseInt(toID(args.join(''))) || 10, 'Rank', true];
const html = tools.board(...boardArgs);
if (typeof html !== 'string') return Bot.pm(by, 'Something went wrong.', Bot.log(html));
if (tools.hasPermission(by, 'gamma', room) && tools.canHTML(room)) {
return Bot.say(room, '/adduhtml LB, <div style="max-height:320px;overflow-y:scroll"><center>' + html + '</center></div>');
} else return Bot.sendHTML(by, '<div style="max-height:320px;overflow-y:scroll"><center>' + html + '</center></div>');
}
};
<file_sep>/pmcommands/readmail.js
module.exports = {
help: `Reads the latest message in your inbox!`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
// TODO: Migrate to MongoDB
const user = toID(by);
const mails = Bot.DB('mails').get(user);
if (!mails || !mails.length) return Bot.pm(by, "Nope, no unread mails!");
if (!Bot.lmp) Bot.lmp = {};
delete Bot.lmp[user];
const mail = mails.pop();
const date = new Date(mail.time);
Bot.pm(by, `At ${date.toLocaleTimeString()} GMT on ${date.toDateString()}, ${mail.author} said: ${mail.content}`);
Bot.DB.save();
}
};
<file_sep>/discord/hpl.js
module.exports = {
help: `Collection of HPL links.`,
pm: true,
commandFunction: function (args, message, Bot) {
// eslint-disable-next-line max-len
message.channel.send(new Discord.MessageEmbed().setTitle('HPL II').setColor('#d2def1').addField('Scores', `http://hindi.partman.co.in/hpl-2021/board`).addField('Draft', `http://hindi.partman.co.in/hpl-2021/draft`).addField('\u200b', '\u200b').addField('Weeks', Array.from({ length: 7 }).map((_, num) => `[${num + 1}](http://hindi.partman.co.in/hpl-2021/week${num + 1})`).join(' ')).addField('Playoffs!', `[Semis](http://hindi.partman.co.in/hpl-2021/semifinals)`));
}
};
<file_sep>/public/maze/scene.js
const createScene = function () {
const scene = new BABYLON.Scene(engine);
const light = new BABYLON.HemisphericLight("HemiLight", new BABYLON.Vector3(0, 1, 0), scene);
const camera = new BABYLON.UniversalCamera("MyCamera", new BABYLON.Vector3(-2, 0.5, 1), scene);
camera.minZ = 0.0001;
camera.attachControl(canvas, true);
camera.speed = 0.01;
camera.angularSpeed = 0.05;
camera.angle = Math.PI / 2;
camera.rotation.y = Math.PI / 2;
camera.direction = new BABYLON.Vector3(Math.cos(camera.angle), 0, Math.sin(camera.angle));
scene.activeCameras.push(camera);
const sphere = BABYLON.MeshBuilder.CreateSphere("dummyCamera", { radius: 0.5 }, scene);
sphere.parent = camera;
sphere.rotation.x = Math.PI / 2;
const ground = BABYLON.MeshBuilder.CreateGround("ground", { width: 100, height: 100 }, scene);
pbrGround = new BABYLON.PBRMaterial("pbr", scene);
ground.material = pbrGround;
pbrGround.albedoColor = new BABYLON.Color3(1.0, 0.966, 0.936);
pbrGround.metallic = 1.0;
pbrGround.roughness = 1.0;
const randomNumber = function (min, max) {
if (min === max) {
return min;
}
const random = Math.random();
return random * (max - min) + min;
};
const box = new BABYLON.MeshBuilder.CreateBox("crate", { size: 1, height: 2 }, scene);
box.material = new BABYLON.StandardMaterial("Mat", scene);
const boxUrl = "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/Playground/textures/crate.png";
const boxDiffuse = new BABYLON.Texture(boxUrl, scene);
box.material.diffuseTexture = boxDiffuse;
box.checkCollisions = true;
const boxNb = 6;
const theta = 0;
const radius = 6;
const maze = MAZE.create(20, 20);
const boxes = [box];
maze.forEach((row, x) => {
row.forEach((flag, y) => {
if (flag) return;
const newBox = box.clone(`box${x}-${y}`);
boxes.push(newBox);
newBox.position = new BABYLON.Vector3(x, 1, y);
});
});
boxes.shift().dispose();
scene.gravity = new BABYLON.Vector3(0, -0.9, 0);
scene.collisionsEnabled = true;
camera.checkCollisions = true;
camera.applyGravity = true;
ground.checkCollisions = true;
camera.ellipsoid = new BABYLON.Vector3(0.4, 0.5, 0.4);
camera.ellipsoidOffset = new BABYLON.Vector3(0, 0.5, 0);
// Camera management
camera.inputs.removeByType("FreeCameraKeyboardMoveInput");
camera.inputs.removeByType("FreeCameraMouseInput");
const FreeCameraKeyboardWalkInput = function () {
this._keys = [];
this.keysUp = [38];
this.keysDown = [40];
this.keysLeft = [37];
this.keysRight = [39];
};
FreeCameraKeyboardWalkInput.prototype.attachControl = function (noPreventDefault) {
const _this = this;
const engine = this.camera.getEngine();
const element = engine.getInputElement();
if (!this._onKeyDown) {
element.tabIndex = 1;
this._onKeyDown = function (evt) {
if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
_this.keysDown.indexOf(evt.keyCode) !== -1 ||
_this.keysLeft.indexOf(evt.keyCode) !== -1 ||
_this.keysRight.indexOf(evt.keyCode) !== -1) {
const index = _this._keys.indexOf(evt.keyCode);
if (index === -1) {
_this._keys.push(evt.keyCode);
}
if (!noPreventDefault) {
evt.preventDefault();
}
}
};
this._onKeyUp = function (evt) {
if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
_this.keysDown.indexOf(evt.keyCode) !== -1 ||
_this.keysLeft.indexOf(evt.keyCode) !== -1 ||
_this.keysRight.indexOf(evt.keyCode) !== -1) {
const index = _this._keys.indexOf(evt.keyCode);
if (index >= 0) {
_this._keys.splice(index, 1);
}
if (!noPreventDefault) {
evt.preventDefault();
}
}
};
element.addEventListener("keydown", this._onKeyDown, false);
element.addEventListener("keyup", this._onKeyUp, false);
}
};
FreeCameraKeyboardWalkInput.prototype.detachControl = function () {
const engine = this.camera.getEngine();
const element = engine.getInputElement();
if (this._onKeyDown) {
element.removeEventListener("keydown", this._onKeyDown);
element.removeEventListener("keyup", this._onKeyUp);
BABYLON.Tools.UnregisterTopRootEvents([
{ name: "blur", handler: this._onLostFocus }
]);
this._keys = [];
this._onKeyDown = null;
this._onKeyUp = null;
}
};
FreeCameraKeyboardWalkInput.prototype.checkInputs = function () {
if (this._onKeyDown) {
const camera = this.camera;
for (let index = 0; index < this._keys.length; index++) {
const keyCode = this._keys[index];
const speed = camera.speed;
if (this.keysLeft.indexOf(keyCode) !== -1) {
camera.rotation.y -= camera.angularSpeed;
camera.direction.copyFromFloats(0, 0, 0);
} else if (this.keysUp.indexOf(keyCode) !== -1) {
camera.direction.copyFromFloats(0, 0, speed);
} else if (this.keysRight.indexOf(keyCode) !== -1) {
camera.rotation.y += camera.angularSpeed;
camera.direction.copyFromFloats(0, 0, 0);
} else if (this.keysDown.indexOf(keyCode) !== -1) {
camera.direction.copyFromFloats(0, 0, -speed);
}
if (camera.getScene().useRightHandedSystem) {
camera.direction.z *= -1;
}
camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
BABYLON.Vector3.TransformNormalToRef(camera.direction, camera._cameraTransformMatrix, camera._transformedDirection);
camera.cameraDirection.addInPlace(camera._transformedDirection);
}
}
};
FreeCameraKeyboardWalkInput.prototype._onLostFocus = function (e) {
this._keys = [];
};
FreeCameraKeyboardWalkInput.prototype.getClassName = function () {
return "FreeCameraKeyboardWalkInput";
};
FreeCameraKeyboardWalkInput.prototype.getSimpleName = function () {
return "keyboard";
};
camera.inputs.add(new FreeCameraKeyboardWalkInput());
const FreeCameraSearchInput = function (touchEnabled) {
if (touchEnabled === void 0) {
touchEnabled = true;
}
this.touchEnabled = touchEnabled;
this.buttons = [0, 1, 2];
this.angularSensibility = 2000.0;
this.restrictionX = 100;
this.restrictionY = 60;
};
FreeCameraSearchInput.prototype.attachControl = function (noPreventDefault) {
const _this = this;
const engine = this.camera.getEngine();
const element = engine.getInputElement();
const angle = { x: 0, y: 0 };
if (!this._pointerInput) {
this._pointerInput = function (p, s) {
const evt = p.event;
if (!_this.touchEnabled && evt.pointerType === "touch") {
return;
}
if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
return;
}
if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
try {
evt.srcElement.setPointerCapture(evt.pointerId);
} catch (e) {
// Nothing to do with the error. Execution will continue.
}
_this.previousPosition = {
x: evt.clientX,
y: evt.clientY
};
if (!noPreventDefault) {
evt.preventDefault();
element.focus();
}
} else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
try {
evt.srcElement.releasePointerCapture(evt.pointerId);
} catch (e) {
// Nothing to do with the error.
}
_this.previousPosition = null;
if (!noPreventDefault) {
evt.preventDefault();
}
} else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
if (!_this.previousPosition || engine.isPointerLock) {
return;
}
const offsetX = evt.clientX - _this.previousPosition.x;
const offsetY = evt.clientY - _this.previousPosition.y;
angle.x += offsetX;
angle.y -= offsetY;
if (Math.abs(angle.x) > _this.restrictionX) {
angle.x -= offsetX;
}
if (Math.abs(angle.y) > _this.restrictionY) {
angle.y += offsetY;
}
if (_this.camera.getScene().useRightHandedSystem) {
if (Math.abs(angle.x) < _this.restrictionX) {
_this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
}
} else {
if (Math.abs(angle.x) < _this.restrictionX) {
_this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
}
}
if (Math.abs(angle.y) < _this.restrictionY) {
_this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
}
_this.previousPosition = {
x: evt.clientX,
y: evt.clientY
};
if (!noPreventDefault) {
evt.preventDefault();
}
}
};
}
this._onSearchMove = function (evt) {
if (!engine.isPointerLock) {
return;
}
const offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
const offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
if (_this.camera.getScene().useRightHandedSystem) {
_this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
} else {
_this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
}
_this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
_this.previousPosition = null;
if (!noPreventDefault) {
evt.preventDefault();
}
};
const pointerEvent = BABYLON.PointerEventTypes.POINTERDOWN |
BABYLON.PointerEventTypes.POINTERUP |
BABYLON.PointerEventTypes.POINTERMOVE;
this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, pointerEvent);
element.addEventListener("mousemove", this._onSearchMove, false);
};
FreeCameraSearchInput.prototype.detachControl = function () {
const engine = this.camera.getEngine();
const element = engine.getInputElement();
if (this._observer && element) {
this.camera.getScene().onPointerObservable.remove(this._observer);
element.removeEventListener("mousemove", this._onSearchMove);
this._observer = null;
this._onSearchMove = null;
this.previousPosition = null;
}
};
FreeCameraSearchInput.prototype.getClassName = function () {
return "FreeCameraSearchInput";
};
FreeCameraSearchInput.prototype.getSimpleName = function () {
return "MouseSearchCamera";
};
camera.inputs.add(new FreeCameraSearchInput());
return scene;
};
<file_sep>/commands/boardgames/othellosequence.js
module.exports = {
cooldown: 10000,
help: `Displays the moves for the shortest Othello match.`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `d6 c4 d3 c6 b5 e6 d7 c5 f5`);
}
};
<file_sep>/discord/allhints.js
const PZ = require('../data/PUZZLES/index.js');
module.exports = {
help: `Displays all the hints left with each team.`,
guildOnly: PZ.guildID,
commandFunction: function (args, message, Bot) {
if (!message.member.roles.cache.has(PZ.IDs.staff)) {
return message.channel.send('Access denied.').then(msg => msg.delete({ timeout: 3000 }));
}
const Discord = require('discord.js'), embed = new Discord.MessageEmbed();
embed.setColor('#F1C40F').setTitle('Hints Remaining').addFields(PZ.allTeams().map(team => PZ.getTeam(team)).map(team => {
return {
name: team.name,
value: team.hints
};
}));
message.channel.send(embed);
}
};
<file_sep>/commands/boardgames/mengywave.js
module.exports = {
cooldown: 100,
help: `㋛`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `㋛^^㋛㋛^^㋛\\\\㋛㋛\\\\`.repeat(~~args.join('')));
}
};
<file_sep>/pmcommands/hpl.js
module.exports = {
help: `HPL links.`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
const text = `HPL Finals (II): ${websiteLink}/hpl/week7 | Draft: ${websiteLink}/hpl/draft`;
Bot.pm(by, text);
}
};
<file_sep>/discord/pm.js
module.exports = {
help: `PMs () ()`,
admin: true,
guildOnly: ['719076445699440700'],
commandFunction: function (args, message, Bot) {
args = args.join(' ').split(/,/);
if (!args.length) return message.channel.send(unxa);
Bot.pm(args[0], args.slice(1).join(','));
}
};
<file_sep>/discord/puzzle.js
const PZ = require('../data/PUZZLES/index.js');
module.exports = {
help: `Displays a puzzle.`,
guildOnly: PZ.guildID,
commandFunction: function (args, message, Bot) {
if (!PZ.live && message.channel.id !== PZ.IDs.staffChannel) {
return message.channel.send('Sorry, this command may not be used at this time. \'o.o');
}
const team = PZ.getTeam(message.channel.id);
if (!team && ![/* PZ.finishChannel, */PZ.IDs.staffChannel].includes(message.channel.id)) {
return message.channel.send('Can\'t be used here.');
}
if (!args.length) return message.channel.send('Which puzzle?');
const puzzle = PZ.getPuzzle(toID(args.join('')));
if (!puzzle || team && !team.unlocked.includes(puzzle.index)) return message.channel.send('Puzzle not found.');
message.channel.send(PZ.displayPuzzle(puzzle.id));
}
};
<file_sep>/discord/say.js
module.exports = {
help: `Does stuff.`,
admin: true,
pm: true,
commandFunction: function (args, message, Bot) {
if (message.guild.id === '719076445699440700') return Bot.say(message.channel.name, args.join(' '));
message.channel.send(args.join(' '));
message.delete();
}
};
<file_sep>/commands/pokemongo/hostban.js
module.exports = {
cooldown: 0,
help: `Bans a user from hosting raids`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
const protoDB = require('origindb')('data/POGO'), DB = protoDB('users');
// eslint-disable-next-line prefer-const
let [id, ...reason] = args.join(' ').split(',');
id = toID(id);
if (!id) return Bot.roomReply(room, by, `Please mention the user you plan on defenestrating`);
const user = DB.get(id);
if (!user) return Bot.roomReply(room, by, `Uhh, I don't think ${id} is a registered user...`);
if (user.hostBanned || user.raidBanned) {
return Bot.roomReply(room, by, `B-but they're already ${user.hostBanned ? 'host' : 'raid'}banned D:`);
}
user.hostBanned = true;
DB.set(id, user);
return Bot.roomReply(room, by, `${user.displayName} has been absolutely YEETED from hosting raids`);
}
};
<file_sep>/commands/groupchat-battledome-strategy/roll.js
module.exports = {
cooldown: 1,
help: `Rolls stuff.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
const rollStr = `!roll ${args.length ? args.join(' ') : '20'}`;
Bot.say(room, tools.hasPermission(by, 'gamma') ? rollStr : `/w ${by},${rollStr}`);
}
};
<file_sep>/pmcommands/buyitem.js
module.exports = {
help: `Buys an item from a room. Syntax: ${prefix}buyitem (room), (item ID | confirm)`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
let user = toID(by);
const cargs = args.join(' ').split(/\s*,\s*/);
if (!cargs[1]) return Bot.pm(by, unxa);
const room = cargs.shift().toLowerCase().replace(/[^a-z0-9-]/g, '');
if (!room || !Bot.rooms[room]) return Bot.pm(by, 'Invalid room.');
if (!Bot.rooms[room].shop) return Bot.pm(by, 'Sorry, that room doesn\'t have a Shop.');
const shop = Bot.rooms[room].shop, lb = Bot.rooms[room].lb;
const id = toID(cargs.join(''));
if (id === 'confirm') {
if (!Bot.rooms[room].shop.temp[user]) return Bot.pm(by, 'You don\'t have anything to confirm!');
const item = Bot.rooms[room].shop.inventory[Bot.rooms[room].shop.temp[user]];
user = lb.users[user];
if (!user) return Bot.pm(by, "Couldn't find your details, sorry.");
for (let i = 0; i < user.points.length; i++) {
if (user.points[i] < item.cost[i]) {
Bot.pm(by, 'Something went wrong with your purchase. You have not been charged.');
return Bot.log("URGENT: Price limiter fail!");
}
}
try {
client.channels.cache.get(shop.channel).send(`${by.substr(1)} bought: ${item.name}.`);
} catch (e) {
Bot.log('Unable to send purchase confirmation.', item, by);
Bot.pm(by, 'Your purchase has gone through. Please contact PartMan.');
}
user.points[0] -= item.cost[0];
user.points[1] -= item.cost[1];
tools.updateLB(room);
delete Bot.rooms[room].shop.temp[toID(by)];
tools.updateShops(room);
return Bot.pm(by, `Your purchase of ${item.name} has been noted! Staff will get back to you soon. <3`);
}
if (!shop.inventory[id]) return Bot.pm(by, 'Sorry, it doesn\'t look like that item is available.');
Bot.pm(by, `Selected item: ${shop.inventory[id].name}${shop.inventory[id].desc ? ` (${shop.inventory[id].desc})` : ''}.`);
user = lb.users[user];
if (!user) return Bot.pm(by, 'Sorry, it looks like you can\'t afford that yet!');
if (user.points.length !== shop.inventory[id].cost.length || user.points.length !== lb.points.length) {
return Bot.pm(by, 'Sorry, this went terribly wrong - the item in question has not been coded properly.');
}
for (let i = 0; i < user.points.length; i++) {
if (!(user.points[i] >= shop.inventory[id].cost[i])) {
return Bot.pm(by, `Insufficient balance - you need ${shop.inventory[id].cost[i]} more ${lb.points[i][2]}.`);
}
}
Bot.rooms[room].shop.temp[toID(by)] = id;
const item = shop.inventory[id];
// eslint-disable-next-line max-len
Bot.pm(by, `You have chosen to buy: ${item.name} for ${tools.listify(lb.points.map((a, i) => item.cost[i] + a[2]))}. Send \`\`${prefix}buyitem ${Bot.rooms[room].title.startsWith('groupchat-') ? room : Bot.rooms[room].title}, confirm\`\` to confirm within a minute.`);
return setTimeout(() => {
if (Bot.rooms[room].shop.temp[toID(by)]) {
Bot.pm(by, 'Your purchase has timed out.');
delete Bot.rooms[room].shop.temp[toID(by)];
}
}, 60000);
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/dping7.js
module.exports = {
cooldown: 10000,
help: `Pings on Discord.`,
permissions: 'alpha',
commandFunction: function (Bot, room, time, by, args, client) {
if (args[0] && typelist.includes(toID(args[0]))) {
client.channels.get('549432010322477056').send('Type: ' + tools.toName(toID(args[0])) + ' Tour started!');
Bot.say(room, 'Sent.');
const tourArr = JSON.parse(fs.readFileSync('./data/DATA/tourrecords.json', 'utf8'));
tourArr.push({ official: false, type: toID(args[0]), starter: toID(by), time: Date.now(), gen: 7 });
fs.writeFileSync('./data/DATA/tourrecords.json', JSON.stringify(tourArr));
} else Bot.say(room, 'Type not found.');
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/tourrecords.js
// TODO: Replace tourrecords with an actual database
module.exports = {
cooldown: 50000,
help: `Displays the record of Tours created.`,
permissions: 'alpha',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `/addhtmlbox <DETAILS><SUMMARY>Tour Records</SUMMARY>${JSON.parse(fs.readFileSync('./data/DATA/tourrecords.json')).map(t => tools.colourize(tools.toName(t.starter)) + (t.official ? '<B>' : '') + ' > ' + (t.official ? '</B>' : '') + tools.colourize(tools.toName(t.type)) + ' (' + tools.toHumanTime(Date.now() - t.time) + ' ago)').join('<BR>')}</DETAILS>`);
}
};
<file_sep>/handlers/battle.js
// TODO: Have various handlers for custom responses
exports.handler = function (room, message, isIntro, args) {
args = Array.from(args);
let game = BattleAI.games[room];
switch (args[0]) {
case 'request': {
if (isIntro) break;
if (args[1]) {
args.shift();
try {
let obj = JSON.parse(args.join('|')), temp;
if (!game && !obj.selfPassed) temp = args.join('|');
if (game?.temp && obj.selfPassed) {
obj = JSON.parse(game.temp);
delete game.temp;
}
if (toID(obj.side.name) !== toID(Bot.status.nickName)) return Bot.say(room, `THIS ISN'T ME AAAA`);
Bot.say(room, `/timer on`);
if (!game) game = BattleAI.newGame(room, obj.side);
if (temp) game.temp = temp;
// Bot.say(room, '!code ' + JSON.stringify(obj, null, 2));
if (!game.started) {
if (room.startsWith('battle-gen8metronomebattle-')) {
game.started = true;
game.tier = '[Gen 8] Metronome Battle';
Bot.say(room, `G'luck!`);
game.noSwitch = true;
} else return;
}
if (obj.side) game.side = obj.side;
if (obj.active) game.active = obj.active;
if (game.tier === '[Gen 8] Metronome Battle') return Bot.say(room, `/choose move 1,move 1`);
if (obj.forceSwitch) return Bot.say(room, `/choose switch ${game.switchPick(true)}`);
else {
setTimeout(() => {
const pick = game.switchPick();
if (pick && (obj.active && obj.active[0] ? !obj.active[0].trapped : true)) {
return Bot.say(room, `/switch ${pick}`);
} else return Bot.say(room, `/move ${game.pickMove()}`);
}, 100);
}
} catch (e) {
console.log(e);
}
}
break;
}
case 'poke': {
if (isIntro) break;
if (game && args[1] !== game.side.id) return game.enemyTeam.push(args[2].split(', ')[0]);
break;
}
case 'tier': {
if (isIntro) break;
if (!game) return;
Bot.say(room, `G'luck!`);
game.tier = args[1];
if (['[Gen 8] Random Battle', '[Gen 8] Super Staff Bros 4 (Wii U)'].includes(game.tier)) {
if (game.tier === '[Gen 8] Super Staff Bros 4 (Wii U)') {
game.ai = 0;
game.noSwitch = true;
}
game.started = true;
Bot.emit('battle', room, ``, false, ['request', '{ "selfPassed": true }']);
}
break;
}
case 'teampreview': {
if (isIntro) break;
if (!game) break;
return Bot.say(room, `/team ${game.firstPick()}`);
}
case 'faint': {
if (isIntro || !game) break;
if (args[2] && !args[1].startsWith(game.side.id)) return game.enemyTeam.remove(args[2].split(', ')[0]);
break;
}
case '-boost': {
if (isIntro) break;
if (!game) return;
if (args[1].startsWith(game.side.id)) {
game.selfBoosts[args[2]] += parseInt(args[3]);
} else game.enemyData.boosts[args[2]] += parseInt(args[3]);
break;
}
case '-setboost': {
if (isIntro) break;
if (!game) return;
if (args[1].startsWith(game.side.id)) {
game.selfBoosts[args[2]] = parseInt(args[3]);
} else game.enemyData.boosts[args[2]] = parseInt(args[3]);
break;
}
case '-unboost': {
if (isIntro) break;
if (!game) return;
if (args[1].startsWith(game.side.id)) {
game.selfBoosts[args[2]] -= parseInt(args[3]);
} else game.enemyData.boosts[args[2]] -= parseInt(args[3]);
break;
}
case '-miss': {
if (isIntro) break;
return Bot.say(room, 'F');
}
case '-crit': {
if (isIntro) break;
return Bot.say(room, '>crit');
}
case '-sidestart': {
if (isIntro) break;
if (!game) return;
if (args[1].startsWith(game.side.id)) {
if (args[2] === 'move: Stealth Rock') {
game.sideHazards.sr = true;
} else if (args[2] === 'move: Spikes') {
game.sideHazards.spikes = game.sideHazards.spikes ? game.sideHazards.spikes + 1 : 1;
} else if (args[2] === 'move: Toxic Spikes') {
game.sideHazards.tspikes = game.sideHazards.tspikes ? game.sideHazards.tspikes + 1 : 1;
}
} else {
if (args[2] === 'move: Stealth Rock') {
game.setHazards.sr = true;
} else if (args[2] === 'move: Spikes') {
game.setHazards.spikes = game.setHazards.spikes ? game.setHazards.spikes + 1 : 1;
} else if (args[2] === 'move: Toxic Spikes') {
game.setHazards.tspikes = game.setHazards.tspikes ? game.setHazards.tspikes + 1 : 1;
}
}
break;
}
case '-item': {
if (isIntro) break;
if (!game) return;
if (!args[1].startsWith(game.side.id)) return game.enemyData.item = args[2];
break;
}
case '-enditem': {
if (isIntro) break;
if (!game) return;
if (!args[1].startsWith(game.side.id)) return game.enemyData.item = null;
break;
}
case '-ability': {
if (isIntro) break;
if (!game) return;
if (!args[1].startsWith(game.side.id)) return game.enemyData.ability = args[2];
break;
}
case '-sideend': {
if (isIntro) break;
if (!game) return;
if (args[1].startsWith(game.side.id)) {
if (args[2] === 'move: Stealth Rock') game.sideHazards.sr = false;
else if (args[2] === 'move: Spikes') game.sideHazards.spikes = 0;
else if (args[2] === 'move: Toxic Spikes') game.sideHazards.tspikes = 0;
} else {
if (args[2] === 'move: Stealth Rock') game.setHazards.sr = false;
else if (args[2] === 'move: Spikes') game.setHazards.spikes = 0;
else if (args[2] === 'move: Toxic Spikes') game.setHazards.tspikes = 0;
}
break;
}
case 'switch': {
if (isIntro || !game) break;
if (args[1] && args[1].startsWith(game.side.id)) game.setActiveBoosts();
else {
game.enemy = args[2].split(', ')[0];
game.setEnemyData();
}
break;
}
case 'win': {
if (game && toID(args[1]) !== toID(Bot.status.nickName)) Bot.say(room, 'Welp, GG!');
else if (game) Bot.say(room, 'Well played! GG!');
else Bot.say(room, 'GG, both!');
Bot.say(room, '/part');
if (game) {
/*
if (game.tier === '[Gen 8] Super Staff Bros 4 (Wii U)' && config.autoLadder) {
Bot.say('', '/search gen8superstaffbros4wiiu');
}
*/
return delete BattleAI.games[room];
} else return;
}
}
};
<file_sep>/data/VR/TC7/water.js
exports.water = {
sp: [],
s: ["Ludicolo"],
sm: [],
ap: ["Lanturn"],
a: ["Gyarados-Mega", "Starmie "],
am: ["Relicanth"],
bp: ["Lapras", "Gyarados", "Carracosta"],
b: ["Swampert-Mega", "Tentacruel", "Slowking"],
bm: ["Primarina", "Kingler", "Kingdra", "Volcanion"],
cp: ["Azumarill", "Keldeo", "<NAME>", "Marill", "Goldeen", "Seaking"],
c: ["Crawdaunt", "Blastoise-Mega", "Empoleon"],
cm: ["Golisopod", "Toxapex"],
d: ["Gastrodon"],
e: ["Suicune", "Wartortle"],
unt: [],
bans: ["Greninja", "Rotom-Wash"]
};
<file_sep>/data/VR/TC7/normal.js
exports.normal = {
sp: ["Audino-Mega", "Bewear"],
s: ["Porygon-Z"],
sm: ["Staraptor"],
ap: ["Blissey"],
a: ["Chansey"],
am: ["Ditto", "Lopunny-Mega"],
bp: ["Type-Null"],
b: [],
bm: ["Slaking"],
cp: [],
c: ["Porygon2"],
cm: [],
d: [],
e: [],
unt: ["Staravia", "Diggersby", "Bouffalant", "Furfrou", "Munchlax", "Dodrio", "Toucannon", "Heliolisk", "Kecleon"],
bans: ["Meloetta"]
};
<file_sep>/commands/groupchat-partbot-1v1tc/lasttours.js
module.exports = {
cooldown: 10000,
help: `Displays a record of the last 10 Tours created.`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `/addhtmlbox <DETAILS><SUMMARY>Recent Tours</SUMMARY>${JSON.parse(fs.readFileSync('./data/DATA/tourrecords.json', 'utf8')).sort((a, b) => b.time - a.time).splice(0, 10).map(t => tools.colourize(tools.toName(t.starter)) + (t.official ? '<B>' : '') + ' > ' + (t.official ? '</B>' : '') + tools.colourize(tools.toName(t.type)) + ' (' + tools.toHumanTime(Date.now() - t.time) + ' ago)').join('<BR>')}</DETAILS>`);
}
};
<file_sep>/pmcommands/checkword.js
module.exports = {
help: `Checks whether a given word is Scrabble-legal. Syntax: \`\`${prefix}checkword word(, dict, mod)\`\``,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
const [word, dict, mod] = args.join('').split(',');
const WORDS = require('../data/WORDS/index.js');
const text = `${toID(word).toUpperCase()} is ${WORDS.checkWord(word, dict, mod) ? '' : 'not '} a Scrabble-legal word.`;
Bot.pm(by, text);
}
};
<file_sep>/data/VR/TC7/fairy.js
exports.fairy = {
sp: [],
s: ["Primarina", "<NAME>"],
sm: ["Gardevoir-Mega", "Klefki"],
ap: ["Togekiss", "<NAME>", "Mawile-Mega", "Whimsicott"],
a: ["Dedenne"],
am: ["<NAME>", "Azumarill", "Ninetales-a"],
bp: [],
b: ["Clefable"],
bm: [],
cp: ["Diancie-Mega"],
c: ["Granbull"],
cm: [],
d: [],
e: [],
unt: ["Comfey", "Shiinotic"],
bans: ["Magearna"]
};
<file_sep>/commands/global/deletejoinphrase.js
module.exports = {
cooldown: 10,
help: `Deletes a joinphrase. Syntax: ${prefix}deletejoinphrase (user)`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
const name = toID(args.join(''));
if (!Bot.jps[room] || !Bot.jps[room][name]) return Bot.say(room, `It doesn\'t look like that user has a joinphrase...`);
delete Bot.jps[room][name];
fs.writeFile(`./data/JPS/${room}.json`, JSON.stringify(Bot.jps[room], null, 2), e => {
if (e) return console.log(e);
Bot.say(room, 'Joinphrase deleted!');
});
}
};
<file_sep>/commands/boardgames/rmmg.js
module.exports = {
cooldown: 0,
help: `Random Mastermind guesses!`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, Math.floor(Math.random() * 4096).toString(8).padStart(4, '0'));
}
};
<file_sep>/commands/global/invite.js
module.exports = {
cooldown: 100,
help: `Invites people to a groupchat.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args.length) return Bot.say(room, 'No name detected.');
if (!room.startsWith('groupchat-')) return Bot.say(room, 'Not a groupchat.');
args.join(' ').split(',').forEach(user => Bot.say(room, `/invite ${user}`));
}
};
<file_sep>/commands/global/whattimeis.js
module.exports = {
cooldown: 100,
help: `Translates time A to time B given timezones. For example: \`\`${prefix}whattimeis 6:30 AM IST in EST\`\``,
permissions: 'none',
commandFunction: function (Bot, room, sentTime, by, args, client, isPM) {
const input = args.join(' ');
if (!input) return Bot.pm(by, unxa);
// eslint-disable-next-line max-len
const match = input.match(/(?: ?is ?)?(\d{1,2}(?:\:\d{2}){0,2})(?: ?o['"`’ʼ]? ?clock)? ?([ap]m)?(?: ([a-z]{3,4}?))? (?:in|to) ([a-z]{3,4}?)/i);
// TODO: Add GMT±\d+ to parsing
if (!match) {
// eslint-disable-next-line max-len
return Bot.pm(by, `Hiya; I wasn't able to parse your sentence! If you feel it should've been valid, please contact PartMan.`);
}
let time = 0; // (0 @ 12:00:00 AM)
let [, timestamp, meridian, baseZone, targetZone] = match;
if (!baseZone) baseZone = 'GMT';
[baseZone, targetZone] = [baseZone.toLowerCase(), targetZone.toLowerCase()];
const tz = require('../../data/DATA/timezones.json');
baseZone = tz.find(z => [z.abbr, z.value].map(toID).includes(baseZone));
targetZone = tz.find(z => [z.abbr, z.value].map(toID).includes(targetZone));
if (!baseZone || !targetZone) {
return Bot.pm(by, `Unrecognized timezone: Could not find ${baseZone ? `target` : `specified base`} time zone`);
}
let tfh = 0;
if (!meridian) tfh = 1;
meridian = meridian ? meridian.toLowerCase() : 'am';
const timesplit = timestamp.split(':');
if (timesplit[0] === '12') timesplit[0] = '0';
if (meridian === 'pm') time += 12 * 60 * 60 * 1000;
time += timesplit.reduce((acc, val, index) => {
return acc + ~~toID(val) * [60, 60, 1000].slice(index).reduce((a, b) => a * b, 1);
}, 0);
const today = new Date();
function getTimeZoneOffset (timeZone) {
return new Date(today.toLocaleString('GMT', { timeZone: timeZone.utc[0] })) - today;
}
const delta = getTimeZoneOffset(targetZone) - getTimeZoneOffset(baseZone);
const targetTimeval = time + delta;
const targetSeconds = Math.round(targetTimeval / 1000);
let relFlag;
const dayLength = 24 * 60 * 60 * 1;
function formatSeconds (targetSeconds) {
if (targetSeconds < 0) {
relFlag = 0;
targetSeconds += dayLength;
} else if (targetSeconds > dayLength) {
relFlag = 2;
targetSeconds -= dayLength;
} else relFlag = 1;
const timeVals = [];
timeVals.unshift(Math.floor(targetSeconds / (60 * 60)));
targetSeconds -= timeVals[0] * (60 * 60);
timeVals.unshift(Math.floor(targetSeconds / 60));
targetSeconds -= timeVals[0] * 60;
timeVals.unshift(Math.floor(targetSeconds));
timeVals.reverse();
const tfht = timeVals.map((num, i) => String(num).padStart(i ? 2 : 1, '0')).join(':');
let targetMer = 'AM';
if (timeVals[0] > 12) {
targetMer = 'PM';
timeVals[0] -= 12;
} else if (timeVals[0] === 12) {
targetMer = 'PM';
} else if (timeVals[0] === 0) {
timeVals[0] = 12;
}
const tht = `${timeVals.map((num, i) => String(num).padStart(i ? 2 : 1, '0')).join(':')} ${targetMer}`;
return [tht, tfht];
}
const baseTime = formatSeconds(Math.round(time / 1000)), targetTime = formatSeconds(targetSeconds);
const dateOffset = [' on the previous day.', '.', ' on the next day.'][relFlag];
const output = `${baseTime[tfh]} in ${baseZone.value} is ${targetTime[tfh]} in ${targetZone.value}${dateOffset}`;
const cleaned = output.replace(/(?::00)+(?= )/g, '');
if (isPM) Bot.pm(by, cleaned);
else if (tools.hasPermission(by, room, 'gamma')) Bot.say(room, cleaned);
else Bot.roomReply(room, by, cleaned);
}
};
<file_sep>/pmcommands/alts.js
module.exports = {
help: `Checks for alts of the given user. Requires you to be roomstaff in one of PartBot's rooms.`,
permissions: 'none',
commandFunction: async function (Bot, by, args, client) {
for (let r in Bot.rooms) {
r = Bot.rooms[r];
if (['public', 'hidden'].includes(r.type)) {
if (tools.hasPermission(by, 'beta', toID(r.title)) || /^[%@*&]/.test(by)) {
const user = toID(args.join(''));
if (!user) return Bot.pm(by, `Whose?`);
const alts = await DATABASE.getAlts(user);
if (!alts.length) return Bot.pm(by, `${user} has no known alts.`);
// eslint-disable-next-line max-len
return Bot.sendHTML(by, `<details><summary>${user}'s alts [${alts.length}]</summary><hr />${alts.sort().join(', ')}</details>`);
}
}
}
return Bot.pm(by, 'Access denied.');
}
};
<file_sep>/commands/global/pat.js
module.exports = {
cooldown: 1000,
help: `Pats a user.`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `/me pats ${args.length ? args.join(' ') : by.substr(1)}`);
}
};
<file_sep>/commands/global/chainreaction.js
function gameTimer (game, turn) {
const time = 45;
if (!Bot.rooms[game.room]) return;
if (!Bot.rooms[game.room].gameTimers) Bot.rooms[game.room].gameTimers = {};
const gameTimers = Bot.rooms[game.room].gameTimers;
clearTimeout(gameTimers['onlygame']);
gameTimers['onlygame'] = setTimeout(() => Bot.say(game.room, `${turn} hasn't played for the past ${time} seconds...`), time * 1000);
}
function clearGameTimer (game) {
clearTimeout(Bot.rooms[game.room]?.gameTimers?.['onlygame']);
}
module.exports = {
help: `Guide (courtesy bro torterra, SaltiestCactus23, and Stan the Nova): https://docs.google.com/document/d/1Ft1M-h7TRDrkEz4LdWoSygmty8XDsRpd2S5HyF_9e1Y`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client, isPM) {
if (!args.length) args.push('help');
switch (toID(args.shift())) {
case 'help': case 'h': {
if (isPM) return Bot.roomReply(room, by, this.help);
return Bot.say(room, this.help);
break;
}
case 'join': case 'j': {
const game = Bot.rooms[room].chainreaction;
if (!game) return Bot.roomReply(room, by, 'Nope, no Chain Reaction here.');
if (game.started) return Bot.roomReply(room, by, 'F in being too late.');
const pls = Object.keys(game.players);
if ((game.beeg ? pls >= 15 : pls >= 8) || pls >= game.height * game.width) return Bot.roomReply(room, by, "Sorry, hit the player cap. ;-;");
if (game.addPlayer(by.substr(1))) return Bot.say(room, `${by.substr(1)} joined the game!`);
return Bot.roomReply(room, by, "You're already in it. o.o");
break;
}
case 'leave': case 'l': {
if (!Bot.rooms[room].chainreaction) return Bot.roomReply(room, by, 'Nope, no Chain Reaction here.');
if (Bot.rooms[room].chainreaction.started) return Bot.roomReply(room, by, 'F in being too late.');
if (Bot.rooms[room].chainreaction.removePlayer(by.substr(1))) {
return Bot.say(room, `${by.substr(1)} left the game!`);
}
return Bot.roomReply(room, by, "Join first, nerd.");
break;
}
case 'new': case 'n': {
if (isPM) return Bot.roomReply(room, by, "Games can only be created in chat.");
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, "Access denied.");
if (Bot.rooms[room].chainreaction) return Bot.roomReply(room, by, 'One\'s going on.');
if (!(['boardgames'].includes(room) && tools.hasPermission(by, 'gamma', room)) && !tools.hasPermission(by, 'beta', room)) return Bot.roomReply(room, by, 'Access denied.');
let dimensions = [9, 6];
let beeg = false;
if (args[0] === 'beeg' && tools.hasPermission(by, 'admin')) {
dimensions = [15, 15];
beeg = true;
args = [];
}
args = args.join(' ').split(/[ ,x]/);
if (args.length) {
args = args.map(t => parseInt(t));
if (args.length === 2 && !isNaN(args[0]) && !isNaN(args[1])) {
if (args[0] > 15 || args[0] < 1 || args[1] > 15 || args[1] < 1) return Bot.say(room, "Not a good board size.");
else if (args[0] * args[1] < 5) return Bot.say(room, "Board too smol.");
else dimensions = args;
}
}
Bot.rooms[room].chainreaction = GAMES.create('chainreaction', ...dimensions, room, beeg);
Bot.say(room, `A ${beeg ? 'BEEG ' : ''}game of Chain Reaction has been created! Use \`\`${prefix}chainreaction join\`\` to join!`);
break;
}
case 'start': case 's': {
if (!Bot.rooms[room].chainreaction) return Bot.roomReply(room, by, 'Nope, no Chain Reaction here.');
if (!(['boardgames'].includes(room) && tools.hasPermission(by, 'gamma', room)) && !tools.hasPermission(by, 'beta', room)) return Bot.roomReply(room, by, 'Access denied.');
if (Bot.rooms[room].chainreaction.started) return Bot.roomReply(room, by, 'F in being too late.');
if (Object.keys(Bot.rooms[room].chainreaction.players).length < 2) return Bot.say(room, "Not enough players. ;-;");
Bot.rooms[room].chainreaction.start();
break;
}
case 'click': {
const CR = Bot.rooms[room].chainreaction;
if (!CR) return Bot.roomReply(room, by, 'Nope, no Chain Reaction here.');
if (!CR.started) return Bot.roomReply(room, by, 'Not started. -_-');
if (!args.length == 2) return Bot.roomReply(room, by, unxa);
if (CR.turn !== toID(by) || CR.displaying) return;
const boards = CR.tap(parseInt(args.shift()), parseInt(args.shift()), CR.players[toID(by)].col);
if (!boards || !boards.length) return Bot.roomReply(room, by, 'Just click an empty spot or your own colour, nerd.');
new Promise((resolve, reject) => {
if (CR.timer) clearGameTimer(CR);
function displayQueue () {
if (!boards.length) return resolve();
Bot.say(room, `/adduhtml CR, ${boards.shift()}`);
setTimeout(displayQueue, 1000);
}
CR.displaying = true;
displayQueue();
}).then(() => {
CR.displaying = false;
const winner = CR.nextTurn();
const turn = CR.turn;
if (winner) {
Bot.say(room, `/adduhtml CRGRATZ, Game ended! GG! Congratulations to <font color="${CR.players[winner].col}">@</font>${tools.escapeHTML(CR.players[winner].name)}!`);
clearGameTimer(CR);
delete Bot.rooms[room].chainreaction;
} else {
const messages = [
"{NAME} donut it's your turn go play",
"{UNAME} AAAAAA GO PLAY",
"Psst {NAME} play already",
"{NAME} murder time Y/Y",
"When click @{NAME}",
"Yo {NAME} thoughts on boom?",
"{UNAME} LET'S GO KABOOM",
"WOOO EXPLOSIONS {UNAME} DON'T DISAPPOINT ME",
"{NAME} eenie meenie miney BLOW!",
"{NAME} I blame you for not playing fast enough",
"WEE WOO WEE WOO {UNAME}",
"<i>hugs {NAME}</i>",
"<i>bullies {NAME}</i>",
"{NAME} you're a nerd",
"The mood for murder has struck, {NAME}",
"{UNAME} CLICKCLICKCLICKCLICK",
"{NAME} play or I SD14 you",
"{UNAME} I SEEK THE BLOOD OF MY ENEMIES",
"/ban {NAME}, Took too long",
"{NAME}. You are the chosen one.",
"{NAME}, harbinger of doom.",
"{NAME} i-it's not like I want you to c-click quickly, b-baka! >///<",
"{NAME} if you don't play you're going to bed without dinner tonight",
",egg {NAME}"
];
Bot.say(room, `/sendprivatehtmlbox ${CR.players[turn].name}, <div class="chat chatmessage-partbot highlighted"><small>[PRIVATE] </small><strong style="color:#8b5ec9;"><small>*</small><span class="username" data-roomgroup="*" data-name="PartBot">PartBot</span>:</strong> <em>${messages.random().replace(/{NAME}/g, CR.players[turn].name).replace(/{UNAME}/g, CR.players[turn].name.toUpperCase())}</em></div>`);
gameTimer(CR, CR.players[turn].name);
}
}).catch();
break;
}
case 'end': case 'e': {
if (!(['boardgames'].includes(room) && tools.hasPermission(by, 'gamma', room)) && !tools.hasPermission(by, 'beta', room)) return Bot.roomReply(room, by, 'Access denied.');
const CR = Bot.rooms[room].chainreaction;
if (!CR) return Bot.say(room, "Didn't have one active anyways.");
clearGameTimer(CR);
delete Bot.rooms[room].chainreaction;
Bot.say(room, "Game ended!");
break;
}
case 'disqualify': case 'dq': case 'modkill': case 'mk': {
if (!(['boardgames'].includes(room) && tools.hasPermission(by, 'gamma', room)) && !tools.hasPermission(by, 'beta', room)) return Bot.roomReply(room, by, 'Access denied.');
if (isPM) return Bot.roomReply(room, by, "Do it in chat, onegai");
const CR = Bot.rooms[room].chainreaction;
if (!CR) return Bot.say(room, "Didn't have one active anyways.");
const user = toID(args.join(''));
if (!CR.PL.includes(user)) return Bot.say(room, "That user is not in the game.");
if (!CR.order.includes(user)) return Bot.say(room, "That user is already eliminated. 'o.o");
if (CR.turn === user) CR.nextTurn();
CR.order.remove(user);
Bot.say(room, `${CR.players[user].name} has been disqualified.`);
if (!CR.DQs) CR.DQs = [];
CR.DQs.push(user);
if (CR.order.length < 2) {
return CR.end();
}
return;
break;
}
case 'board': case 'b': {
if (!Bot.rooms[room].chainreaction) return Bot.roomReply(room, by, "C-can't find one. ;-;");
if (!Bot.rooms[room].chainreaction.started) return Bot.roomReply(room, by, `Let is start onegai`);
if (!tools.hasPermission(by, 'gamma', room)) return Bot.sendHTML(by, Bot.rooms[room].chainreaction.display());
Bot.say(room, "/adduhtml CR, " + Bot.rooms[room].chainreaction.display());
break;
}
case 'pl': case 'playerlist': case 'players': case 'order': case 'o': case 'turnorder': case 'to': {
const CR = Bot.rooms[room].chainreaction;
if (!CR) return Bot.roomReply(room, by, "Players of a non-existent game, surprisingly, do not exist.");
const html = "<hr/>" + CR.order.map(u => CR.players[u]).map(u => `<b style="color:${u.col};">${u.name.replace(/</g, '<')}</b>`).join(', ') + "<hr/>";
if (tools.hasPermission(by, 'gamma', room)) Bot.say(room, `/adduhtml CRPLAYERS,${html}`);
else Bot.sendHTML(by, html);
break;
}
case 'sub': {
if (!(['boardgames'].includes(room) && tools.hasPermission(by, 'gamma', room)) && !tools.hasPermission(by, 'beta', room)) return Bot.roomReply(room, by, 'Access denied.');
if (isPM) return Bot.roomReply(room, by, "Say it in chat you coward");
if (!Bot.rooms[room].chainreaction) return Bot.say(room, "Don't have a game active.");
args = args.join(' ').split(/\s*,\s*/);
if (args.length !== 2) return Bot.say(room, unxa);
const CR = Bot.rooms[room].chainreaction;
const ids = args.map(toID);
if (Object.keys(CR.players).includes(ids[0]) && Object.keys(CR.players).includes(ids[1])) return Bot.say(room, 'The one you\'re subbing in is already a player!');
if (!Object.keys(CR.players).includes(ids[0]) && !Object.keys(CR.players).includes(ids[1])) return Bot.say(room, "Neither of those are in the game.");
const going = Object.keys(CR.players).includes(ids[1]) ? args[1] : args[0], coming = Object.keys(CR.players).includes(ids[1]) ? args[0] : args[1];
if (coming === toID(Bot.status.nickName)) return Bot.say(room, 'NO U');
CR.players[toID(coming)] = Object.assign({}, CR.players[toID(going)]);
CR.players[toID(coming)].name = coming;
delete CR.players[toID(going)];
CR.order = CR.order.map(id => id === toID(going) ? toID(coming) : id);
CR.PL = CR.PL.map(id => id === toID(going) ? toID(coming) : id);
if (CR.turn === toID(going)) CR.turn = toID(coming);
Object.keys(CR.colours).forEach(col => {
if (CR.colours[col] === toID(going)) CR.colours[col] = toID(coming);
});
Bot.say(room, `/adduhtml CR, ${CR.display()}`);
Bot.say(room, `[[ ]]${going} has been subbed with ${coming}!`);
break;
}
}
}
};
<file_sep>/commands/pokemongo/plop.js
module.exports = {
cooldown: 10,
help: `Plop.`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `plop`);
}
};
<file_sep>/commands/botdevelopment/drumroll.js
module.exports = {
cooldown: 100,
help: `DRUMROLL`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `**DRRRRRRRRR**\n**Drumroll!**`);
}
};
<file_sep>/pmcommands/quovadis.js
module.exports = {
help: `Use ${prefix}help quovadis in a chatroom for complete information.`,
noDisplay: true,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
if (!args.length) return;
if (!args.shift().toLowerCase() === 'play') return;
const arg = args.join(' ').split(/, */);
let room = arg.shift();
room = tools.getRoom(room);
if (!Bot.rooms[room]) return Bot.pm(by, "Invalid room.");
return Bot.commandHandler('quovadis', by, ['play'].concat(arg.join(', ').split(' ')), room, true);
}
};
<file_sep>/commands/global/age.js
module.exports = {
cooldown: 1000,
help: `Displays the age of a user.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args[0]) args.push(by);
const perms = tools.hasPermission(by, 'gamma', room);
require('request')('http://pokemonshowdown.com/users/' + toID(args.join(' ')) + '.json', (err, response, body) => {
if (err) throw err;
const userObj = JSON.parse(body);
if (!userObj.registertime) return Bot.pm(by, toID(args.join(' ')) + ' is not registered.');
const dtime = Date.now() - 1000 * userObj.registertime;
if (perms) Bot.say(room, userObj.username + ' is ' + tools.toHumanTime(dtime) + ' old.');
else Bot.pm(by, userObj.username + ' is ' + tools.toHumanTime(dtime) + ' old.');
});
}
};
<file_sep>/handlers/discord_chat.js
exports.handle = (message, Bot) => {
};
<file_sep>/discord/puzzlehelp.js
const PZ = require('../data/PUZZLES/index.js');
module.exports = {
help: `Displays a list of usable commands.`,
guildOnly: PZ.guildID,
commandFunction: function (args, message, Bot) {
message.channel.send(PZ.help(message.channel.id === PZ.IDs.staffChannel));
}
};
<file_sep>/commands/pokemongo/register.js
module.exports = {
cooldown: 0,
help: `Registers you in the PoGo room!`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client, isPM) {
// eslint-disable-next-line max-len
const HTML = `<center><form data-submitsend="/msgroom ${room}, /botmsg ${Bot.status.nickName},${prefix}pogoregister IGN: {ign}, Code: {friendcode}, Level: {level}" style="padding:15px;"><table><tr><td><label for="ign">Pokemon Go username: </label></td><td><input type="text" id="ign" name="ign" style="width:180px;"/></td></tr><tr><td><label for="friendcode">Pokemon Go Friend Code: </label></td><td><input type="text" id="friendcode" name="friendcode" style="width:100px;"/></td></tr><tr><td><label for="level">Pokemon Go level: </label></td><td><input type="text" id="level" name="level" style="width:20px;"/></td></tr></table><br/><input type="submit" value="Register!"></form></center>`;
if (!isPM && tools.hasPermission(by, 'gamma', room)) Bot.say(room, `/addhtmlbox ${HTML}`);
else if (typeof isPM === 'string') Bot.sendHTML(isPM, HTML);
else Bot.say(room, `/sendprivatehtmlbox ${by}, ${HTML}`);
}
};
<file_sep>/discord/sayas.js
module.exports = {
help: `Says as () in ()`,
admin: true,
guildOnly: ['719076445699440700'],
commandFunction: function (args, message, Bot) {
args = args.join(' ').split(/,\s*/);
if (!args.length) return message.channel.send(unxa);
if (/^[a-zA-Z0-9]/.test(args[0])) args[0] = ' ' + args[0];
// eslint-disable-next-line
Bot.emit('chat', message.channel.name, Date.now(), args[0].trim().replace(/^[^\^$+%@*#&~]/, c => ' ' + c), args.slice(1).join(','));
}
};
<file_sep>/commands/global/runas.js
module.exports = {
cooldown: 10,
help: `Runs commands from another room.`,
permissions: 'admin',
commandFunction: function (Bot, room, time, by, args, client) {
let [inRoom, msg] = args.join(' ').split('|');
inRoom = tools.getRoom(inRoom);
if (!msg) return Bot.roomReply('Oi');
const nArgs = msg.trim().split(' '), command = toID(nArgs.shift());
try {
require(`../${inRoom}/${tools.commandAlias(command)}.js`).commandFunction(Bot, room, time, by, nArgs, client);
} catch (e) {
Bot.roomReply(room, by, `${require('util').inspect(e)}`);
}
}
};
<file_sep>/data/GAMES/linesofaction.js
class LoA {
constructor (id, room, restore) {
this.room = room.toLowerCase().replace(/[^a-z0-9-]/g, '');
this.id = id;
this.board = Array.from({ length: 8 }).map(row => Array.from({ length: 8 }).map(cell => 0));
for (let i = 1; i < 7; i++) this.board[0][i] = this.board[7][i] = 'W';
for (let i = 1; i < 7; i++) this.board[i][0] = this.board[i][7] = 'B';
this.W = {
name: '',
player: ''
};
this.B = {
name: '',
player: ''
};
this.turn = null;
this.started = false;
if (restore) Object.keys(restore).forEach(key => this[key] = restore[key]);
}
other () {
switch (this.turn) {
case 'W': return 'B';
case 'B': return 'W';
default: return null;
}
}
piecesOnLine (x, y, hor, ver) {
if (x > 7 || x < 0 || y > 7 || y < 0) return null;
let m = Number(Boolean(hor)), n = Number(Boolean(ver));
let counter = 0;
if (!m && !n) [m, n] = [-1, 1];
for (let i = 1; i < 8 && x + i * m < 8 && x + i * m > 0 && y + i * n < 8 && y + i * n > 0; i++) {
if (this.board[x + i * m][y + i * n]) counter++;
}
for (let i = 1; i < 8 && x - i * m < 8 && x - i * m > 0 && y - i * n < 8 && y - i * n > 0; i++) {
if (this.board[x - i * m][y - i * n]) counter++;
}
if (this.board[x][y]) counter++;
return counter;
}
display (sel, hl, side) {
let str = '<center><table style="border-collapse:collapse;" border="1px solid black;">';
for (let i = 0; i < 8; i++) {
str += `<tr style="height: 35px;">`;
for (let j = 0; j < 8; j++) {
// eslint-disable-next-line max-len
str += `<td style="width: 35px; background-color: green; vertical-align: middle; horizontal-align: center; text-align: center;">${this.board[i][j] ? `<span style="width: 30px; height: 30px; border-radius: 50%; border: 1px solid black; display: inline-block; margin: auto; vertical-align: middle; background-color: ${this.board[i][j] === 'W' ? 'white' : 'black'};"></span>` : `<button style="height: 35px; width: 35px; border: none; background: transparent;" name="send" value="/msg ${Bot.status.nickName}, ${prefix}linesofaction ${this.room} click ${i},${j}"></button>`}</td>`;
}
str += `</tr>`;
}
str += '</table></center>';
return str;
}
start () {
if (!this.W.player || !this.B.player) return null;
this.turn = 'B';
this.started = true;
return true;
}
nextTurn (idled) {
}
}
module.exports = LoA;
<file_sep>/commands/global/boardtest.js
module.exports = {
cooldown: 1,
help: ``,
permissions: 'coder',
commandFunction: function (Bot, room, time, by, args, client) {
delete require.cache[require.resolve('../../data/board.js')];
Bot.say(room, '/addhtmlbox ' + require('../../data/board.js').board(
['Name', 'Points'],
[['PartMan', 100], ['Hydro', 200], ['<NAME>', 10]],
data => data[1],
[
// eslint-disable-next-line max-len
"font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:2px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aaa;color:#fff;background-color:#f38630;font-weight:bold;border-color:inherit;text-align:left;vertical-align:top;",
// eslint-disable-next-line max-len
"font-family:Arial, sans-serif;padding:2px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aaa;color:#333;background-color:#fff;background-color:#FCFBE3;border-color:inherit;text-align:center;vertical-align:top;font-weight:bold;",
// eslint-disable-next-line max-len
"font-family:Arial, sans-serif;padding:2px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#aaa;color:#333;background-color:#fff;border-color:inherit;text-align:center;vertical-align:top;font-weight:bold;"
],
args, 'Rank'));
}
};
<file_sep>/commands/global/do.js
module.exports = {
cooldown: 0,
help: `Does stuff.`,
permissions: 'admin',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `${args[0] ? args.join(' ') : '/me does nothing'}`);
}
};
<file_sep>/discord/confessionconfirm.js
module.exports = {
help: `Approves a confessional.`,
guildOnly: '773859244163465223',
commandFunction: function (args, message, Bot) {
if (message.channel.id !== '781114745713066034') {
return message.channel.send('This cannot be used here.').then(msg => msg.delete({ timeout: 3000 }));
}
const channel = client.channels.cache.get('781124564381597766');
const origindb = require('origindb'), cdb = origindb('data/KGPDB'), confs = cdb('confessions').object();
const id = toID(args.join('')).replace(/[^0-9]/g, '');
if (id > confs.amt) return message.channel.send(`The highest ID is ${confs.amt}...`);
if (!confs.list[id]) return message.channel.send('Something went wrong!');
const con = confs.list[id];
if (con.rejected) return message.channel.send('This confession has already been rejected!');
if (con.confirmed) return message.channel.send('This confession has already been confirmed!');
channel.send(`\`\`\`\n#${id}\n\n` + con.content + '\n```');
message.channel.send('Confession confirmed.');
con.confirmed = true;
con.confirmer = message.author.id;
cdb.save();
client.users.cache.get(con.author).send(`Your confession has been approved! (ID: ${id})`);
}
};
<file_sep>/commands/botdevelopment/botcommands.js
module.exports = {
cooldown: 10000,
help: `Displays the Gist with some information on PS Bot commands.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `https://gist.github.com/PartMan7/573d25eff91cab704ab8539822131591`);
}
};
<file_sep>/commands/pokemonunite/dt.js
// TODO: HOLY SHIT REFACTOR THIS
/* eslint-disable max-len */
module.exports = {
cooldown: 0,
help: `Information about all characters in Unite! Syntax \`\`${prefix}dt mon[, level (optional)]\`\``,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client, redir) {
let [pkmn, lv] = args.join('').split(',');
pkmn = toID(pkmn);
if (lv) lv = lv.replace(/\D/ig, '');
lv = ~~lv;
if (lv < 1) lv = 15;
if (lv > 15) return Bot.roomReply(room, by, `Invalid level (${lv})`);
let html = 'Not found', key;
const mon = data.unitedex.find(m => toID(m.name) === pkmn);
if (mon) {
key = pkmn;
const stats = data.unitestats.find(m => m.name === mon.name).level[lv - 1];
const hst = { ...data.unitestats[0].level[lv - 1] };
data.unitestats.forEach(stat => {
Object.entries(stat.level[lv - 1]).forEach(([k, v]) => {
if (hst[k] < v) hst[k] = v;
});
});
html = nunjucks.render('unite/character.njk', { mon, lv, hst, stats, redir }).replace(/[\n\t]/g, '');
}
const battle = data.uniteitems.battle.find(m => toID(m.name) === pkmn);
if (battle) {
key = battle.name;
html = `<div><div style="float:left"><img src="https://d275t8dp8rxb42.cloudfront.net/items/battle/${battle.name.replace(/ /g, '+')}.png" style="margin:10px 0" height="100" width="100"/></div><div style="overflow:hidden;vertical-align:top;padding:15px"><span style="font-size:1.3em;font-weight:bold">${battle.name}</span><span style="padding:10px;font-size:0.7em;border-radius:5px;margin:0 5px;background-color:rgba(128,128,128,0.2);fill:#ffd283"><img src="https://i.postimg.cc/yk8dFtSP/newcooldown.png" height="20" width="20" style="vertical-align:middle;"/> ${battle.cooldown}s</span><p>${battle.description}</p></div></div>`;
}
const held = data.uniteitems.held.find(m => toID(m.name) === pkmn);
if (held) {
key = held.name;
const bonuses = [1, 2, 3].map(n => held[`bonus${n}`]).filter(x => x);
html = `<img src="https://d275t8dp8rxb42.cloudfront.net/items/held/${held.name.replace(/ /g, '+')}.png" style="float:left" height="100" width="100"/><div style="overflow:hidden;vertical-align:top;padding:15px"><div style="font-size:1.3em;font-weight:bold">${held.name}</div>${bonuses.length ? `<div>Bonus${bonuses.length === 1 ? '' : 'es'}: <b style="color:#22bb77">${bonuses.join(', ')}</b></div>` : ''}<p>${held.description1}</p></div>`;
}
if (redir) return html;
if (tools.hasPermission(by, 'gamma', room)) Bot.say(room, `/adduhtml unite${key}, ${html || 'Not found!'}`);
else Bot.say(room, `/sendprivateuhtml ${by}, unite${key}, ${html || 'Not found.'}`);
return;
}
};
<file_sep>/commands/global/scrabble.js
function gameTimer (game, turn) {
const time = 120;
if (!Bot.rooms[game.room]) return;
if (!Bot.rooms[game.room].gameTimers) Bot.rooms[game.room].gameTimers = {};
const gameTimers = Bot.rooms[game.room].gameTimers;
clearTimeout(gameTimers[game.id]);
// TODO: (For all games) Make timer mention game
gameTimers[game.id] = setTimeout(() => Bot.say(game.room, `${turn} hasn't played for the past ${time} seconds...`), time * 1000);
}
function clearGameTimer (game) {
clearTimeout(Bot.rooms[game.room]?.gameTimers?.[game.id]);
}
module.exports = {
help: `Scrabble! \`\`${prefix}scrabble new\`\`, \`\`${prefix}scrabble join\`\`, and \`\`${prefix}scrabble start\`\``,
permissions: 'none',
findGame: (by, context, games, type) => {
by = toID(by);
if (context && games[context]) return games[context];
if (~~context) return null;
const gs = Object.values(games);
if (gs.length === 1) return gs[0];
const cargs = (context || '').toString().split(/(?:,|\s+v(?:er)?s(?:us)?\.?\s+)/).map(toID);
if (type !== 'sub' && cargs.length >= 2 && cargs.length <= 4) {
const fgs = gs.filter(game => !cargs.find(u => !game.players[u]));
if (fgs.length === 1) return fgs[0];
}
switch (type) {
case 'join': {
const fgs = gs.filter(game => !game.started && !game.players[by]);
if (fgs.length === 1) return fgs[0];
break;
}
case 'start': {
const fgs = gs.filter(game => !game.started);
if (fgs.length === 1) return fgs[0];
break;
}
case 'gamerule': {
const fgs = gs.filter(game => !game.placed.flat().find(tile => tile));
if (fgs.length === 1) return fgs[0];
break;
}
case 'action': {
const fgs = gs.filter(game => by ? game.players[by] : true);
if (fgs.length === 1) return fgs[0];
break;
}
case 'watch': {
const fgs = gs.filter(game => by ? !(game.players[by] || game.spectators.includes(by)) : true);
if (fgs.length === 1) return fgs[0];
break;
}
case 'unwatch': {
const fgs = gs.filter(game => by ? game.spectators.includes(by) : true);
if (fgs.length === 1) return fgs[0];
break;
}
case 'sub': {
if (cargs.length !== 2) break;
const fgs = gs.filter(game => {
return game.players[cargs[0]] && !game.players[cargs[1]] || game.players[cargs[1]] && !game.players[cargs[0]];
});
if (fgs.length === 1) return fgs[0];
}
}
return null;
},
commandFunction: function (Bot, room, time, by, args, client, isPM) {
if (!args.length) args.push('help');
switch (toID(args[0])) {
case 'help': case 'h': case 'aaaa': {
// eslint-disable-next-line max-len
const help = 'The Scrabble module! For Scrabble rules, visit https://scrabble.hasbro.com/en-us/rules. You can play just by clicking on the board and typing your words!';
if (tools.hasPermission(by, 'gamma', room) && !isPM) Bot.say(room, help);
else Bot.roomReply(room, by, help);
break;
}
case 'new': case 'n': case 'create': case 'newgame': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (isPM) return Bot.roomReply(room, by, "Do it in the room ya nerd");
if (!tools.canHTML(room)) return Bot.say(room, `I need * permissions for this`);
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = Bot.rooms[room].scrabble;
const ID = Date.now();
$[ID] = GAMES.create('scrabble', ID, room);
// eslint-disable-next-line max-len
Bot.say(room, `/adduhtml SCRABBLE-${ID}, <hr><h1>Scrabble Signups have begun!</h1><button name="send" value="/msg ${Bot.status.nickName}, ${prefix}scrabble ${room}, join ${ID}">Join!</button><hr>`);
// eslint-disable-next-line max-len
Bot.say(room, '/notifyrank all, Scrabble, A new game of Scrabble has been created!, A new game of Scrabble has been created.');
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
break;
}
case 'join': case 'j': case 'iwanttoplaytoo': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame(by, args.slice(1).join(' '), Bot.rooms[room].scrabble, 'join');
if (!$) return Bot.roomReply(room, by, 'No game specified/found');
const user = toID(by);
$.addPlayer(by.replace(/^[^a-zA-Z0-9]/, '')).then(() => {
Bot.say(room, `${by.substr(1)} joined the game!`);
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
}).catch(err => Bot.roomReply(room, by, err));
break;
}
case 'leave': case 'l': case 'part': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame(by, args.slice(1).join(' '), Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, 'No game specified/found');
$.removePlayer(by.replace(/^[^a-zA-Z0-9]/, '')).then(() => {
Bot.say(room, `${by.substr(1)} left the game!`);
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
}).catch(err => Bot.roomReply(room, by, err));
break;
}
case 'start': case 's': case 'hajime': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame('', args.slice(1).join(' '), Bot.rooms[room].scrabble, 'start');
if (!$) return Bot.roomReply(room, by, 'No game specified/found');
$.start().then(() => {
// eslint-disable-next-line max-len
Bot.say(room, `/adduhtml SCRABBLE-${$.id},<hr>${tools.listify(Object.values($.players).map(u => tools.colourize(u.name)))}! <div style="text-align: right; display: inline-block; font-size: 0.9em; float: right;"><button name="send" value="/msg ${Bot.status.nickName}, ${prefix}scrabble ${room} spectate ${$.id}">Watch!</button></div><hr>`);
$.spectators.forEach(u => Bot.say(room, $.HTML(u)));
Object.keys($.players).forEach(u => Bot.say(room, $.HTML(u)));
Bot.say(room, $.highlight());
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
}).catch(err => Bot.log(err));
break;
}
case 'play': case 'place': case 'p': case 'click': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame(by, args[1], Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, "Game not found");
if (!$.isTurn(by)) return Bot.roomReply(room, by, 'Not your turn!');
if (~~args[1]) args.shift();
args.shift();
const coords = args.shift().split(',').map(n => ~~n);
if (coords.length !== 2) return Bot.roomReply(room, by, "You're supposed to click a tile first");
const dir = args.shift();
let down;
switch (toID(dir || '')[0]) {
case 'd': down = true; break;
case 'r': down = false; break;
default: return Bot.roomReply(room, by, `Direction must be right/down, not ${dir}`);
}
const word = args.join('');
$.play(coords, down, word).then(res => {
const [name, score, scores, bingo, receivedTiles] = res;
// eslint-disable-next-line max-len
Bot.say(room, `/adduhtml scrabbleplay${$.id},<hr/>${bingo ? '<b>BINGO!</b> ' : ''}${tools.colourize(name)} scored ${score} (${scores.join('/')})<hr/>`);
if (receivedTiles.includes(' ')) {
// eslint-disable-next-line max-len
Bot.roomReply(room, by, `If you want to use one of your blank tiles, then enter the letter you want the blank to be used as followed by a '. For example, if you’re trying to play the word trace and want to use your blank as a C, then you would type TRAC'E into the ‘Type your word here’ box.`);
}
if (Object.values($.players).find(player => player.tiles.length === 0)) { // Game ends
$.ended = true;
$.deduct();
$.spectators.forEach(u => Bot.say(room, $.HTML(u)));
Object.keys($.players).forEach(u => Bot.say(room, $.HTML(u)));
pName = Object.values($.players).sort((a, b) => b.score - a.score)[0];
Bot.say(room, `Game ended! ${pName.name} won!`);
Bot.say(room, `/adduhtml SCRABBLEBOARD${$.id},${$.boardHTML()}`);
Bot.say(room, `/adduhtml SCRABBLEPOINTS${$.id},${$.pointsHTML()}`);
fs.unlink(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, () => {});
clearGameTimer($);
delete Bot.rooms[room].scrabble[$.id];
return;
}
gameTimer($, $.players[$.order[$.turn]].name);
$.spectators.forEach(u => Bot.say(room, $.HTML(u)));
Object.keys($.players).forEach(u => Bot.say(room, $.HTML(u)));
Bot.say(room, $.highlight());
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
}).catch(e => {
Bot.say(room, $.HTML(by));
Bot.roomReply(room, by, e);
});
break;
}
case 'select': case 'choose': case 'c': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame(by, args[1], Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, "Game not found");
if (!$.isTurn(by)) return Bot.roomReply(room, by, 'Not your turn!');
const player = $.getPlayer($.turn);
args.shift();
if (parseInt(args[0]) > 30) args.shift();
const cargs = args.join(' ').match(/\b\d+\b/g).map(n => ~~n);
if (cargs.length !== 2) return Bot.roomReply(room, by, 'Selections must have exactly two numbers');
player.selected = cargs.join(',');
Bot.say(room, $.HTML(by));
break;
}
case 'openexchange': case 'oe': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame(by, args[1], Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, "Game not found");
if (!$.isTurn(by)) return Bot.roomReply(room, by, 'Not your turn!');
const player = $.getPlayer($.turn);
player.exchange = true;
Bot.say(room, $.HTML(by));
break;
}
case 'closeexchange': case 'ce': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame(by, args[1], Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, "Game not found");
if (!$.isTurn(by)) return Bot.roomReply(room, by, 'Not your turn!');
const player = $.getPlayer($.turn);
player.exchange = false;
Bot.say(room, $.HTML(by));
break;
}
case 'exchange': case 'x': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame(by, args[1], Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, "Game not found");
if (!$.isTurn(by)) return Bot.roomReply(room, by, 'Not your turn!');
const player = $.getPlayer($.turn);
args.shift();
if (parseInt(args[0]) > 30) args.shift();
$.exchange(args.join('')).then(res => {
const newLetters = res[1];
if (newLetters.includes(' ')) {
// eslint-disable-next-line max-len
Bot.roomReply(room, by, `If you want to use one of your blank tiles, then enter the letter you want the blank to be used as followed by a '. For example, if you’re trying to play the word trace and want to use your blank as a C, then you would type TRAC'E into the ‘Type your word here’ box.`);
}
// eslint-disable-next-line max-len
Bot.say(room, `/adduhtml scrabbleplay${$.id},<hr/>${tools.colourize(by.substr(1))} exchanged ${res[0].length} tile(s)<hr/>`);
$.nextTurn();
$.spectators.forEach(u => Bot.say(room, $.HTML(u)));
Bot.say(room, $.highlight());
Object.keys($.players).forEach(u => Bot.say(room, $.HTML(u)));
clearGameTimer($);
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
}).catch(e => {
return Bot.roomReply(room, by, e);
});
break;
}
case 'pass': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame(by, args[1], Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, "Game not found");
if (!$.isTurn(by)) return Bot.roomReply(room, by, 'Not your turn!');
if ($.nextTurn(true)) /* Game ends */ {
$.ended = true;
Bot.say(room, `The match has ended due to passing.`);
$.deduct();
$.spectators.forEach(u => Bot.say(room, $.HTML(u)));
Object.keys($.players).forEach(u => Bot.say(room, $.HTML(u)));
Bot.say(room, `/adduhtml SCRABBLEBOARD${$.id},${$.boardHTML()}`);
Bot.say(room, `/adduhtml SCRABBLEPOINTS${$.id},${$.pointsHTML()}`);
fs.unlink(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, () => {});
clearGameTimer($);
delete Bot.rooms[room].scrabble[$.id];
return;
}
Bot.say(room, `/adduhtml scrabbleplay${$.id},<hr/>${tools.colourize(by.substr(1))} passed<hr/>`);
gameTimer($, $.players[$.order[$.turn]].name);
$.spectators.forEach(u => Bot.say(room, $.HTML(u)));
Object.keys($.players).forEach(u => Bot.say(room, $.HTML(u)));
Bot.say(room, $.highlight());
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
break;
}
case 'end': case 'e': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame('', args.slice(1).join(' '), Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, 'No game specified/found');
Bot.say(room, `/adduhtml SCRABBLE-${$.id},<hr>Ended game #${$.id}<hr>`);
if ($.started) {
$.deduct();
Bot.say(room, `/adduhtml SCRABBLEBOARD${$.id},${$.boardHTML()}`);
Bot.say(room, `/adduhtml SCRABBLEPOINTS${$.id},${$.pointsHTML()}`);
}
fs.unlink(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, () => {});
delete Bot.rooms[room].scrabble[$.id];
break;
}
case 'endsilent': case 'es': case 'endquiet': case 'eq': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame('', args.slice(1).join(' '), Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, 'No game specified/found');
Bot.say(room, `/adduhtml SCRABBLE-${$.id},<hr>Ended game #${$.id}<hr>`);
fs.unlink(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, () => {});
delete Bot.rooms[room].scrabble[$.id];
break;
}
case 'stash': case 'store': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame('', args.slice(1).join(' '), Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, 'No game specified/found');
Bot.say(room, `/adduhtml SCRABBLE-${$.id},<hr>Stashed game #${$.id}<hr>`);
delete Bot.rooms[room].scrabble[$.id];
break;
}
case 'rejoin': case 'rj': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const games = Object.values(Bot.rooms[room].scrabble)
.filter($ => $.players[toID(by)] || $.spectators.includes(toID(by)))
.filter($ => $.started);
if (!games.length) return Bot.roomReply(room, by, 'No game(s) found');
games.forEach($ => Bot.say(room, $.HTML(by)));
break;
}
case 'spectate': case 's': case 'watch': case 'w': case 'see': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
args.shift();
const $ = this.findGame(by, args.join(' '), Bot.rooms[room].scrabble, 'watch');
if (!$) return Bot.roomReply(room, by, 'No game specified/found');
const ID = toID(by);
if ($.getPlayer(ID)) return Bot.roomReply(room, by, "You're a player!");
if ($.spectators.includes(ID)) return Bot.roomReply(room, by, 'You are already spectating this game!');
$.spectators.push(ID);
Bot.say(room, $.HTML(ID));
Bot.roomReply(room, by, `You are now spectating the match of Scrabble!`);
break;
}
case 'unspectate': case 'us': case 'unwatch': case 'uw': case 'unsee': case 'u': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
args.shift();
const $ = this.findGame(by, args.join(' '), Bot.rooms[room].scrabble, 'unwatch');
if (!$) return Bot.roomReply(room, by, 'No game specified/found');
const ID = toID(by);
if ($.getPlayer(ID)) return Bot.roomReply(room, by, "You're a player!");
if (!$.spectators.includes(ID)) return Bot.roomReply(room, by, 'You aren\'t spectating this game!');
$.spectators.remove(ID);
Bot.roomReply(room, by, `You are no longer spectating the match of Scrabble.`);
break;
}
case 'forfeit': case 'leave': case 'f': case 'ff': case 'ihavebeenpwned': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame(by, args[1], Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, "Game not found");
if (!$.getPlayer(by)) return Bot.roomReply(room, by, "You're not a player!");
const isTurn = $.isTurn(by);
$.removePlayer(by).then(res => {
if (res) {
$.ended = true;
Bot.say(room, `The match has ended due to a forfeit.`);
$.deduct();
$.spectators.forEach(u => Bot.say(room, $.HTML(u)));
Object.keys($.players).forEach(u => Bot.say(room, $.HTML(u)));
Bot.say(room, `/adduhtml SCRABBLEBOARD${$.id},${$.boardHTML()}`);
Bot.say(room, `/adduhtml SCRABBLEPOINTS${$.id},${$.pointsHTML()}`);
fs.unlink(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, () => {});
clearGameTimer($);
delete Bot.rooms[room].scrabble[$.id];
return;
}
Bot.say(room, `/adduhtml scrabbleplay${$.id},<hr/>${tools.colourize(by.substr(1))} forfeited<hr/>`);
gameTimer($, $.players[$.order[$.turn]].name);
$.spectators.forEach(u => Bot.say(room, $.HTML(u)));
Object.keys($.players).forEach(u => Bot.say(room, $.HTML(u)));
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
}).catch(e => {
Bot.roomReply(room, by, e);
});
break;
}
case 'backups': case 'bu': case 'stashed': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, "Access denied.");
fs.readdir('./data/BACKUPS', (err, files) => {
if (err) {
Bot.say(room, err);
return Bot.log(err);
}
const games = files
.filter(file => file.startsWith(`scrabble-${room}-`))
.map(file => file.slice(0, -5))
.map(file => file.split('-').pop());
if (games.length) {
Bot.say(room, `/adduhtml SCRABBLEBACKUPS, <details><summary>Game Backups</summary><hr>${games.map(game => {
const $ = require(`../../data/BACKUPS/scrabble-${room}-${game}.json`);
// eslint-disable-next-line max-len
return `<button name="send" value="/msg ${Bot.status.nickName},${prefix}scrabble ${room} restore ${game}">${tools.escapeHTML(tools.listify($.order.map(p => $.players[p].name))) || '(no one)'}</button>`;
}).join('<br>')}</details>`);
} else Bot.say(room, "No backups found.");
});
break;
}
case 'restore': case 'resume': case 'r': {
args.shift();
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, "Access denied.");
const id = parseInt(args.join(''));
if (!id) return Bot.roomReply(room, by, "Invalid ID.");
if (Bot.rooms[room].scrabble?.[id]) return Bot.roomReply(room, by, "Sorry, that game is already in progress!");
fs.readFile(`./data/BACKUPS/scrabble-${room}-${id}.json`, 'utf8', (err, file) => {
if (err) return Bot.roomReply(room, by, "Sorry, couldn't find that game!");
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
Bot.rooms[room].scrabble[id] = GAMES.create('scrabble', id, room, JSON.parse(file));
const $ = Bot.rooms[room].scrabble[id];
Bot.say(room, `The game between ${tools.listify($.order.map(p => $.players[p].name))} has been restored!`);
$.spectators.forEach(u => Bot.say(room, $.HTML(u)));
Object.keys($.players).forEach(u => Bot.say(room, $.HTML(u)));
});
break;
}
case 'menu': case 'm': case 'list': case 'l': case 'players': {
const scrabble = Bot.rooms[room].scrabble;
if (!scrabble || !Object.keys(scrabble).length) {
if (tools.hasPermission(by, 'gamma', room) && !isPM) return Bot.say(room, "Sorry, no games found.");
return Bot.roomReply(room, by, "Sorry, no games found.");
}
const html = `<hr>${Object.keys(scrabble).map(id => {
const $ = scrabble[id];
// eslint-disable-next-line max-len
return `${$.started ? `${tools.listify($.order.map(u => tools.colourize($.players[u].name)))} <button name="send" value="/msg ${Bot.status.nickName},${prefix}scrabble ${room} spectate ${$.id}">Watch!</button>` : `<button name="send" value="/msg ${Bot.status.nickName},${prefix}scrabble ${room} join ${$.id}">Join</button>`}(#${id})`;
}).join('<br>')}<hr>`;
const staffHTML = `<hr>${Object.keys(scrabble).map(id => {
const $ = scrabble[id];
// eslint-disable-next-line max-len
return `${$.started ? `${tools.listify($.order.map(u => tools.colourize($.players[u].name)))} <button name="send" value="/msg ${Bot.status.nickName},${prefix}scrabble ${room} spectate ${$.id}">Watch!</button>` : `<button name="send" value="/msg ${Bot.status.nickName},${prefix}scrabble ${room} join ${$.id}">Join</button>`}<button name="send" value="/msg ${Bot.status.nickName},${prefix}scrabble ${room} end ${$.id}">End</button><button name="send" value="/msg ${Bot.status.nickName},${prefix}scrabble ${room} stash ${$.id}">Stash</button>(#${id})`;
}).join('<br>')}<hr>`;
if (isPM === 'export') return [html, staffHTML];
if (tools.hasPermission(by, 'gamma', room) && !isPM) {
Bot.say(room, `/adduhtml SCRABBLEMENU,${html}`);
Bot.say(room, `/changerankuhtml +, SCRABBLEMENU, ${staffHTML}`);
} else Bot.say(room, `/sendprivatehtmlbox ${by}, ${html}`);
break;
}
case 'disqualify': case 'dq': {
if (!tools.hasPermission(by, 'beta', room)) return Bot.roomReply(room, by, 'Access denied.');
if (isPM) return Bot.roomReply(room, by, 'Scum do it in chat');
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
args.shift();
let context = '';
if (~~args[0]) context = args.shift();
const $ = this.findGame(args.join(' '), context, Bot.rooms[room].scrabble, 'action');
if (!$) return Bot.roomReply(room, by, 'No game specified/found');
const user = toID(args.join(''));
const isTurn = $.isTurn(user);
$.removePlayer(user).then(res => {
if (res) {
$.ended = true;
Bot.say(room, `The match has ended due to a disqualification.`);
$.deduct();
$.spectators.forEach(u => Bot.say(room, $.HTML(u)));
Object.keys($.players).forEach(u => Bot.say(room, $.HTML(u)));
Bot.say(room, `/adduhtml SCRABBLEBOARD${$.id},${$.boardHTML()}`);
Bot.say(room, `/adduhtml SCRABBLEPOINTS${$.id},${$.pointsHTML()}`);
fs.unlink(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, () => {});
delete Bot.rooms[room].scrabble[$.id];
return;
}
if (isTurn) $.nextTurn();
Bot.say(room, `/adduhtml scrabbleplay${$.id},<hr/>${tools.colourize(user)} was DQed<hr/>`);
$.spectators.forEach(u => Bot.say(room, $.HTML(u)));
Object.keys($.players).forEach(u => Bot.say(room, $.HTML(u)));
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
}).catch(e => {
Bot.roomReply(room, by, e);
});
break;
}
case 'bag': case 'left': case 'b': {
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const $ = this.findGame(by, args[1], Bot.rooms[room].scrabble, 'unwatch');
if (!$) return Bot.roomReply(room, by, "Game not found");
const tiles = $.bag.length;
if (isPM) return Bot.pm(by, `The bag has ${tiles} tile(s) left.`);
if (tools.hasPermission(by, 'gamma', room)) Bot.say(room, `The bag has ${tiles} tile(s) left.`);
else Bot.roomReply(room, by, `The bag has ${tiles} tile(s) left.`);
break;
}
case 'sub': case 'substitute': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (isPM) return Bot.roomReply(room, by, 'Scum do it in chat');
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
args.shift();
let context = '';
if (~~args[0]) context = args.shift();
else context = args.join(' ');
const $ = this.findGame('', context, Bot.rooms[room].scrabble, 'sub');
if (!$) return Bot.roomReply(room, by, `Unable to find the game you meant to sub people in!`);
let first;
const ctx = args.join(' ').split(/(?:,|\s+v(?:er)?s(?:us)?\.?\s+)/);
if (ctx.length !== 2) return Bot.roomReply(room, by, `Err, I sub one in and one out; that's how this works`);
if ($.players[toID(ctx[0])] && !$.players[toID(ctx[1])]) first = true;
else if (!$.players[toID(ctx[0])] && $.players[toID(ctx[1])]) first = false;
else {
Bot.log($);
return Bot.roomReply(room, by, 'Something went wrong! (PartMan is investigating)');
}
const going = first ? ctx[0] : ctx[1];
const coming = first ? ctx[1] : ctx[0];
$.players[toID(coming)] = $.players[toID(going)];
delete $.players[toID(going)];
$.players[toID(coming)].name = coming;
$.players[toID(coming)].id = toID(coming);
$.order.splice($.order.indexOf(toID(going)), 1, toID(coming));
$.spectators.remove(toID(coming));
$.spectators.push(toID(going));
Bot.say(room, $.HTML(coming));
Bot.say(room, $.HTML(going));
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
return Bot.say(room, `[[ ]]${going} has been subbed with ${coming}!`);
}
case 'dict': case 'd': case 'dictionary': case 'usedict': case 'ud': case 'usedictionary': case 'use': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const cargs = args.slice(1).join(' ').split(',');
const $ = this.findGame('', cargs[0], Bot.rooms[room].scrabble, 'gamerule');
if (!$) return Bot.roomReply(room, by, 'No game specified/found');
if (!toID(cargs.join(''))) return Bot.say(room, `The current dictionary is ${$.dict?.toUpperCase() || 'CSW21'}.`);
if ($.started && $.placed.flat().find(tile => tile)) {
return Bot.say(room, `You may not change the dictionary after a word has been played.`);
}
if (~~cargs[0]) cargs.shift();
const dict = toID(cargs.join(''));
if (!require('../../data/WORDS/index.js').isDict(dict)) return Bot.say(room, 'Invalid dictionary!');
$.dict = dict;
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
Bot.say(room, `Scrabble #${$.id} is now using ${dict.toUpperCase()}.`);
break;
}
case 'mod': case 'mode': case 'om': case 'gamemode': case 'modify': case 'gamemod': case 'fm': case 'forcemod': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].scrabble) Bot.rooms[room].scrabble = {};
const cargs = args.slice(1).join(' ').split(',');
const $ = this.findGame('', cargs[0], Bot.rooms[room].scrabble, 'gamerule');
if (!$) return Bot.roomReply(room, by, 'No game specified/found');
if ($.started && $.placed.flat().find(tile => tile)) {
return Bot.say(room, `You may not apply a mod after a word has been played.`);
}
if (~~cargs[0]) cargs.shift();
const mod = toID(cargs.join(''));
const modded = $.mod(mod);
if (!modded) return Bot.say(room, `Unable to find that mod!`);
if (modded === 'pokemon' && !['forcemod', 'fm'].includes(toID(args[0]))) {
if (Math.random() < 0.2) {
Bot.say(room, `Uh-oh it looks like I dropped a CRAZY bomb!`);
Bot.say(room, `Scrabble #${$.id} has accidentally enabled the mod CRAZYMONS!`);
$.mod('crazymons');
} else Bot.say(room, `Scrabble #${$.id} has enabled the mod ${mod}.`);
} else Bot.say(room, `Scrabble #${$.id} has enabled the mod ${mod}.`);
fs.writeFile(`./data/BACKUPS/scrabble-${$.room}-${$.id}.json`, JSON.stringify($), e => {
if (e) console.log(e);
});
break;
}
default: Bot.roomReply(room, by, 'No idea what that option was supposed to do');
}
}
};
<file_sep>/commands/global/memory.js
module.exports = {
cooldown: 10000,
help: `Displays the memory usage.`,
permissions: 'coder',
commandFunction: function (Bot, room, time, by, args, client) {
const usageno = process.memoryUsage().heapUsed / 1024 / 1024;
const usagestr = usageno.toString();
const usagearr = usagestr.split('.');
Bot.say(room, `${usagearr[0]}.${usagearr[1].substr(0, 1)} MB`);
}
};
<file_sep>/discord/godb.js
module.exports = {
help: `Updates the GO databases!`,
guildOnly: '292873182677958657',
commandFunction: function (args, message, Bot) {
if (message.channel.id !== '859528623446294538') return message.channel.send('_softly flexes_');
// TODO: rewrite this to use sheets-parser
(() => {
function generateParser (rawHeaders) {
const headers = rawHeaders[0].map((header, i) => [header, rawHeaders[1][i]]);
function dataFromRow (row) {
const obj = {};
const typeMap = {
Boolean: input => ['n', 'no', 'false', '0', '-', ''].includes(input.toLowerCase()) ? false : true,
Integer: input => parseInt(input) || 0,
Number: input => Number(input) || 0,
String: input => String(input)
};
function getType (type) {
const validTypes = ['Boolean', 'String', 'Number'];
if (typeMap.hasOwnProperty(type)) return typeMap[type];
const arrType = Object.keys(typeMap).find(vType => type.startsWith(`<${vType}>`));
if (arrType) return [typeMap[arrType], type.substr(arrType.length + 2) || ','];
return false;
}
headers.forEach(([label, rawType], index) => {
// parse label
const hierarchy = label.split('.');
let parent = obj;
let key = hierarchy[hierarchy.length - 1];
for (let i = 0; i < hierarchy.length - 1; i++) {
const hierarKey = hierarchy[i].replace(/\?$/, '');
if (!parent.hasOwnProperty(hierarKey)) parent[hierarKey] = {};
if (typeof parent[hierarKey] !== 'object') throw new Error(`Path ${hierarchy.slice(0, i + 1).join('.')} already exists as ${parent[hierarchy[i]]}`);
parent = parent[hierarKey];
}
const isArray = key.endsWith('[]');
if (isArray) key = key.slice(0, -2);
const isOptional = key.endsWith('?');
if (isOptional) key = key.slice(0, -1);
if (parent.hasOwnProperty(key)) throw new Error(`Error parsing ${label}: Property '${key}' already exists on object as ${parent[key]}`);
// parse value
const type = getType(rawType);
if (!type) throw new Error(`Unrecognized type ${rawType}`);
if (Array.isArray(type)) {
if (!isArray) throw new Error(`Header conflict (label indicates array while typedef does not)`);
const val = (row[index] === '' ? [] : row[index].split(type[1])).map(type[0]);
if (!isOptional || val.length) parent[key] = val;
} else {
if (isArray) throw new Error(`Header conflict (label does not indicate array while typedef does)`);
const val = type(row[index]);
if (!isOptional || val) parent[key] = val;
}
// Trim optional nests
for (let i = hierarchy.length - 2; i >= 0; i--) {
const subArchy = hierarchy.slice(0, i + 1).map(path => ({ path: path.replace(/\?$/, ''), optional: path.endsWith('?') }));
let lastChild = obj, secondLastChild;
for (const path of subArchy) [secondLastChild, lastChild] = [lastChild, lastChild[path.path]];
if (Object.keys(lastChild).length === 0) delete secondLastChild[subArchy[subArchy.length - 1].path];
}
});
return obj;
}
return dataFromRow;
}
const { sheets } = require('@googleapis/sheets');
const Sheets = sheets({
version: 'v4',
auth: process.env.GOOGLE_API_KEY
});
return Sheets.spreadsheets.values.batchGet({
spreadsheetId: '<KEY>',
ranges: ['#pokedex', '#fast_moves', '#charged_moves']
}).then(res => {
const loaded = res.data.valueRanges.map(sheet => sheet.values);
const dex = {}, fast = {}, charged = {};
const stores = [dex, fast, charged];
loaded.forEach((sheet, i) => {
const parser = generateParser(sheet.splice(0, 2));
const data = sheet.map(parser);
const store = stores[i];
data.forEach(mon => store[toID(mon.name)] = mon);
});
const out = { pokedex: dex, moves: { fast, charged } };
return fs.promises.writeFile('./data/DATA/go.json', JSON.stringify(out, null, '\t'))
.then(() => require('../data/hotpatch.js')('go', message.author.username));
});
})().then(() => {
message.channel.send('It... worked? Damn nice');
}).catch(err => {
Bot.log(err);
message.channel.send(`Uh-oh it crashed\nSince y'all are nerds anyways...\n${err.message}\n\n${err.stack}`);
});
}
};
<file_sep>/commands/global/pick.js
module.exports = {
cooldown: 1000,
help: `Picks between a list of choices, separated by commas.`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
const a = args.join(' ').split(/, ?/g);
Bot.say(room, `${a[0] ? '[[]][[]]' + a[Math.floor(Math.random() * a.length)] : '/me chooses nothing'}`);
}
};
<file_sep>/commands/global/removepoints.js
module.exports = {
cooldown: 100,
help: `Adds points to users. Syntax: ${prefix}addpoints (user1), (user2), (points)`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
if (!Bot.rooms[room].lb) return Bot.say(room, 'This room doesn\'t have a Leaderboard!');
if (!Bot.rooms[room].lb.points[0]) return Bot.pm(by, 'This room doesn\'t have that currency. o.o');
const cargs = args.join(' ').split(/\s*,\s*/);
const cur = Bot.rooms[room].lb.points[0];
let points, flag = false;
const users = [];
for (const thing of cargs) {
if (/[a-z]/i.test(thing)) users.push(thing);
else {
const n = parseInt(thing);
if (isNaN(n)) return Bot.say(room, `Invalid number.`);
if (flag) return Bot.say(room, `Uhh, you gave multiple values of ${cur[1]} to be added.`);
flag = true;
points = n;
}
}
if (!flag) points = 1;
users.forEach(user => tools.addPoints(0, user, -points, room)).then(peeps => {
const list = tools.listify(peeps);
Bot.say(room, `${points} ${points === 1 ? cur[0] : cur[1]} ${points === 1 ? 'was' : 'were'} awarded to ${list}.`);
}).catch(e => {
Bot.say(room, e.message);
});
}
};
<file_sep>/commands/global/commands.js
module.exports = {
cooldown: 10,
help: `Displays a list of commands that can be used by the user. For details of individual commands, use ${prefix}help (command)`,
permissions: 'locked',
commandFunction: function (Bot, room, time, by, args, client) {
const commands = { global: null, pm: null };
const rankLevel = tools.rankLevel(by, room), gLevel = tools.rankLevel(by, 'global');
new Promise((resolve, reject) => {
Object.keys(commands).forEach(category => commands[category] = {
admin: [],
coder: [],
alpha: [],
beta: [],
gamma: [],
none: [],
locked: []
});
// Global commands
fs.readdir('./commands/global', (err, files) => {
if (err) return reject(console.log(err));
files.forEach(file => {
const req = require(`./${file}`);
if (!req || !commands.global[req.permissions] || req.noDisplay) return;
commands.global[req.permissions].push(file.slice(0, file.length - 3));
});
Object.keys(commands.global).forEach(rank => {
if (!commands.global[rank].length && !['none', 'locked'].includes(rank)) delete commands.global[rank];
else commands.global[rank].sort();
});
return resolve();
});
}).then(() => {
return new Promise((resolve, reject) => {
// PM commands
fs.readdir('./pmcommands', (err, files) => {
if (err) return reject(console.log(err));
files.forEach(file => {
const req = require(`../../pmcommands/${file}`);
if (!req || !commands.pm[req.permissions] || req.noDisplay) return;
commands.pm[req.permissions].push(file.slice(0, file.length - 3));
});
Object.keys(commands.pm).forEach(rank => {
if (!commands.pm[rank].length && !['none', 'locked'].includes(rank)) delete commands.pm[rank];
else commands.pm[rank].sort();
});
return resolve();
});
});
}).then(() => {
return new Promise((resolve, reject) => {
// Room commands
fs.readdir(`./commands/${room}`, (err, files) => {
if (err) return resolve();
commands.room = { admin: [], coder: [], alpha: [], beta: [], gamma: [], none: [], locked: [] };
files.forEach(file => {
const req = require(`../${room}/${file}`);
if (!req || !commands.room[req.permissions] || req.noDisplay) return;
commands.room[req.permissions].push(file.slice(0, file.length - 3));
});
Object.keys(commands.room).forEach(rank => {
if (!commands.room[rank].length && !['none', 'locked'].includes(rank)) delete commands.room[rank];
else commands.room[rank].sort();
});
return resolve();
});
});
}).then(() => {
// eslint-disable-next-line max-len
let out = '<hr><details><summary>Commands</summary><hr><details><summary><b>Global Commands</b></summary><hr>These commands can be used in any room.<hr>';
['Admin', 'Coder', 'Alpha', 'Beta', 'Gamma'].forEach(rank => {
if (commands.global[rank.toLowerCase()] && tools.hasPermission(rankLevel, rank.toLowerCase())) {
// eslint-disable-next-line max-len
out += `<details><summary>${rank} Commands</summary><hr>${tools.listify(commands.global[rank.toLowerCase()])}</details><hr>`;
}
});
if (tools.hasPermission(by, 'none', room)) {
commands.global.locked.push(...commands.global.none);
commands.global.locked.sort();
commands.pm.locked.push(...commands.pm.none);
commands.pm.locked.sort();
if (commands.room) {
commands.room.locked.push(...commands.room.none);
commands.room.locked.sort();
}
}
// eslint-disable-next-line max-len
out += `<details><summary>Commands</summary><hr>${tools.listify(commands.global.locked) || 'None.'}</details><hr></details><hr><details><summary><b>PM Commands</b></summary><hr>These commands can be used in PMs.<hr>`;
['Admin', 'Coder', 'Alpha', 'Beta', 'Gamma'].forEach(rank => {
if (commands.pm[rank.toLowerCase()] && tools.hasPermission(gLevel, rank.toLowerCase())) {
// eslint-disable-next-line max-len
out += `<details><summary>${rank} Commands</summary><hr>${tools.listify(commands.pm[rank.toLowerCase()])}</details><hr>`;
}
});
// eslint-disable-next-line max-len
out += `<details><summary>Commands</summary><hr>${tools.listify(commands.pm.locked) || 'None.'}</details><hr></details><hr>`;
if (commands.room) {
// eslint-disable-next-line max-len
out += `<details><summary><b>${Bot.rooms[room] ? Bot.rooms[room].title : tools.toName(room)} Commands</b></summary><hr>These commands can only be used in certain rooms.<hr>`;
['Admin', 'Coder', 'Alpha', 'Beta', 'Gamma'].forEach(rank => {
if (commands.room[rank.toLowerCase()] && tools.hasPermission(rankLevel, rank.toLowerCase())) {
// eslint-disable-next-line max-len
out += `<details><summary>${rank} Commands</summary><hr>${tools.listify(commands.room[rank.toLowerCase()])}</details><hr>`;
}
});
// eslint-disable-next-line max-len
out += `<details><summary>Commands</summary><hr>${tools.listify(commands.room.locked) || 'None.'}</details><hr></details><hr>`;
}
out += '</details><hr>';
Bot.sendHTML(by, out);
});
}
};
<file_sep>/commands/global/connectfour.js
function gameTimer (game, turn) {
const time = 45;
if (!Bot.rooms[game.room]) return;
if (!Bot.rooms[game.room].gameTimers) Bot.rooms[game.room].gameTimers = {};
const gameTimers = Bot.rooms[game.room].gameTimers;
clearTimeout(gameTimers[game.id]);
gameTimers[game.id] = setTimeout(() => Bot.say(game.room, `${turn} hasn't played for the past ${time} seconds...`), time * 1000);
}
function clearGameTimer (game) {
clearTimeout(Bot.rooms[game.room]?.gameTimers?.[game.id]);
}
function sendEmbed (room, winner, players, board, logs, rows) {
Bot.say(room, `http://partbot.partman.co.in/connectfour/${logs}`);
if (!['boardgames'].includes(room)) return;
board = Array.from({ length: board.length }).map((col, x) => Array.from({ length: rows }).map((_, y) => board[x][y] || 'E'));
board.forEach(col => col.reverse());
const Embed = require('discord.js').MessageEmbed, embed = new Embed();
embed.setColor('#0080ff').setAuthor('Connect Four - Room Match').setTitle((winner === 'Y' ? `**${players.Y}**` : players.Y) + ' vs ' + (winner === 'R' ? `**${players.R}**` : players.R)).setURL(`${websiteLink}/connectfour/${logs}`).addField('\u200b', board[0].map((col, i) => board.map(row => row[i])).map(row => row.map(cell => {
switch (cell) {
case 'Y': {
return ':yellow_circle:';
break;
}
case 'R': {
return ':red_circle:';
break;
}
default: return ':blue_circle:';
}
}).join('')).join('\n'));
client.channels.cache.get("576488243126599700").send(embed).catch(e => {
Bot.say(room, 'Unable to send the game to the Discord because ' + e.message);
Bot.log(e);
});
}
function runMoves (run, info, game) {
const room = game.room, id = game.id;
switch (run) {
case 'join': {
const { user, side } = info;
game[side].id = toID(user);
game[side].name = user.replace(/[<>]/g, '');
if (game.Y.id && game.R.id) return runMoves('start', null, game);
const html = `<hr /><h1>Connect Four Signups are active!</h1>${["Y", "R"].filter(side => !game[side].id).map(side => `<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}connectfour ${room}, join ${id} ${side === 'Y' ? 'Yellow' : 'Red'}">${side === 'Y' ? 'Yellow' : 'Red'}</button>`).join(' ')}<hr />`;
return Bot.say(room, `/adduhtml CONNECTFOUR-${id}, ${html}`);
break;
}
case 'start': {
game.started = true;
Bot.say(room, `Connect Four: ${game.Y.name} vs ${game.R.name} GOGO`);
game.spectators.forEach(spect => Bot.sendHTML(spect, `<center><h1>${game[game.turn].name}'s Turn (${game.turn})</h1>${game.boardHTML()}</center>`));
Bot.say(room, `/sendhtmlpage ${game.Y.id}, Connect Four + ${room} + ${id}, ${game.turn === "Y" ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
Bot.say(room, `/sendhtmlpage ${game.R.id}, Connect Four + ${room} + ${id}, ${game.turn === "R" ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
setTimeout(() => {
Bot.say(room, `/highlighthtmlpage ${game.Y.id}, Connect Four + ${room} + ${id}, Your turn!`);
}, 1000);
Bot.say(room, `/adduhtml CONNECTFOUR-${id},<hr />${tools.colourize(game.Y.name)} vs ${tools.colourize(game.R.name)}! <div style="text-align: right; display: inline-block; font-size: 0.9em; float: right;"><button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}connectfour ${room} spectate ${id}">Watch!</button></div><hr />`);
break;
}
case 'move': {
game.spectators.forEach(spect => Bot.say(room, `/sendhtmlpage ${spect}, Connect Four + ${room} + ${id}, <center><h1>${game[game.turn].name}'s Turn (${game.turn})</h1>${game.boardHTML()}</center>`));
Bot.say(room, `/sendhtmlpage ${game.Y.id}, Connect Four + ${room} + ${id}, ${game.turn === "Y" ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
Bot.say(room, `/sendhtmlpage ${game.R.id}, Connect Four + ${room} + ${id}, ${game.turn === "R" ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
setTimeout(() => {
Bot.say(room, `/highlighthtmlpage ${game[game.turn].id}, Connect Four + ${room} + ${id}, Your turn!`);
}, 1000);
break;
}
case 'end': {
clearGameTimer(game);
const players = { Y: game.Y.name, R: game.R.name }, board = game.board, logs = game.moves.join(''), winner = info, rows = game.rows;
fs.unlink(`./data/BACKUPS/connectfour-${room}-${id}.json`, e => {});
Bot.say(room, `/adduhtml CONNECTFOUR-${Date.now()},<center>${game.boardHTML(false, true)}</center>`);
game.spectators.forEach(spect => Bot.say(room, `/sendhtmlpage ${spect}, Connect Four + ${room} + ${id}, <center><h1>Game over!</h1>${game.boardHTML(false)}</center>`));
Bot.say(room, `/sendhtmlpage ${game.Y.id}, Connect Four + ${room} + ${id}, <center><h1>Game over!</h1>${game.boardHTML()}</center>`);
Bot.say(room, `/sendhtmlpage ${game.R.id}, Connect Four + ${room} + ${id}, <center><h1>Game over!</h1>${game.boardHTML()}</center>`);
Bot.say(room, winner && winner !== 'none' ? `${game[winner].name} (${winner === 'Y' ? 'Yellow' : 'Red'}) won!` : 'The game ended as a draw!');
delete Bot.rooms[room].connectfour[id];
sendEmbed(room, winner, players, board, logs, rows);
return;
break;
}
case 'resign': {
clearGameTimer(game);
const loser = info, players = { Y: game.Y.name, R: game.R.name }, board = game.board, logs = game.moves.join(''), winner = loser === 'Y' ? 'R' : 'Y', rows = game.rows;
fs.unlink(`./data/BACKUPS/connectfour-${room}-${id}.json`, e => {});
Bot.say(room, `/adduhtml CONNECTFOUR-${Date.now()},<center>${game.boardHTML(false, true)}</center>`);
game.spectators.forEach(spect => Bot.say(room, `/sendhtmlpage ${spect}, Connect Four + ${room} + ${id}, <center><h1>Resigned.</h1>${game.boardHTML(false)}</center>`));
Bot.say(room, `/sendhtmlpage ${game.Y.id}, Connect Four + ${room} + ${id}, <center><h1>Resigned.</h1>${game.boardHTML()}</center>`);
Bot.say(room, `/sendhtmlpage ${game.R.id}, Connect Four + ${room} + ${id}, <center><h1>Resigned.</h1>${game.boardHTML()}</center>`);
Bot.say(room, `${players[loser]} resigned.`);
delete Bot.rooms[room].connectfour[id];
sendEmbed(room, winner, players, board, logs, rows);
return;
break;
}
}
fs.writeFile(`./data/BACKUPS/connectfour-${room}-${id}.json`, JSON.stringify(game), e => {
if (e) console.log(e);
});
}
module.exports = {
help: `Players take turns dropping a piece into one of the columns (Yellow goes first and red goes second). The first player to connect 4 pieces in a row horizontally, vertically, or diagonally is the winner.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client, isPM) {
if (!args[0]) args.push('help');
switch (args[0].toLowerCase()) {
case 'help': case 'h': {
if (tools.hasPermission(by, 'gamma', room) && !isPM) return Bot.say(room, this.help);
else Bot.roomReply(room, by, this.help);
break;
}
case 'new': case 'n': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (isPM) return Bot.roomReply(room, by, `Thou art stinky, do this in a chatroom`);
if (!tools.canHTML(room)) return Bot.say(room, 'I can\'t do that here. Ask an RO to promote me or something.');
if (!Bot.rooms[room].connectfour) Bot.rooms[room].connectfour = {};
const id = Date.now();
Bot.rooms[room].connectfour[id] = GAMES.create('connectfour', id, {}, room);
Bot.say(room, `/adduhtml CONNECTFOUR-${id}, <hr/><h1>Connect Four Signups have begun!</h1><button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}connectfour ${room}, join ${id} Yellow">Yellow</button><button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}connectfour ${room}, join ${id} Red">Red</button><button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}connectfour ${room}, join ${id} Any">Random</button><hr/>`);
Bot.say(room, '/notifyrank all, Connect Four, A new game of Connect Four has been created!, A new game of Connect Four has been created.');
return;
break;
}
case 'join': case 'j': {
if (!Bot.rooms[room].connectfour) return Bot.roomReply(room, by, 'There isn\'t an active Connect Four game in this room.');
if (!args[1]) return Bot.roomReply(room, by, 'Please specify the ID / side.');
let id, side, user = toID(by), rand = false;
if (args[2] && parseInt(args[1])) {
id = args[1];
side = args[2][0].toUpperCase();
if (side === 'A') {
side = ['Y', 'R'].random();
rand = true;
}
if (!["Y", "R"].includes(side)) return Bot.roomReply(room, by, "I only accept yellow and red. (insert snarky comment)");
} else if (Object.keys(Bot.rooms[room].connectfour).length === 1) {
id = Object.keys(Bot.rooms[room].connectfour)[0];
side = args[1][0].toUpperCase();
if (side === 'A') {
side = ['Y', 'R'].random();
rand = true;
}
if (!["Y", "R"].includes(side)) return Bot.roomReply(room, by, "I only accept yellow and red. (insert snarky comment)");
} else {
side = args[1][0].toUpperCase();
if (side === 'A') {
side = ['Y', 'R'].random();
rand = true;
}
if (!["Y", "R"].includes(side)) return Bot.roomReply(room, by, "I only accept yellow and red. (insert snarky comment)");
id = Object.keys(Bot.rooms[room].connectfour).find(k => {
const game = Bot.rooms[room].connectfour[k];
return game && !game.started && !game[side].id;
});
if (!id) return Bot.roomReply(room, by, "Sorry, unable to find any open games.");
}
const game = Bot.rooms[room].connectfour[id];
if (!game) return Bot.roomReply(room, by, "Nope. BOOP");
if (game.started) return Bot.roomReply(room, by, 'Too late!');
if (game[side].id) return Bot.roomReply(room, by, "Sorry, already taken!");
const other = side === 'Y' ? 'R' : 'Y';
if (game[other].id === user) return Bot.roomReply(room, by, "~~You couldn't find anyone else to fight you? __Really__?~~");
Bot.say(room, `${by.substr(1)} joined Connect Four (#${id}) as ${side === 'Y' ? 'Yellow' : 'Red'}!${rand ? ' (random)' : ''}`);
runMoves('join', { user: by.substr(1), side: side }, game);
break;
}
case 'play': case 'move': case 'click': {
if (!Bot.rooms[room].connectfour) return Bot.roomReply(room, by, 'There isn\'t an active Connect Four game in this room.');
if (!args[1]) return Bot.roomReply(room, by, unxa);
args.shift();
if (!Object.keys(Bot.rooms[room].connectfour).length) return Bot.roomReply(room, by, "No games are active.");
let id, user = toID(by);
if (args[0] && /^\d+$/.test(args[0].trim())) id = args.shift().trim();
else id = Object.keys(Bot.rooms[room].connectfour).find(k => {
const game = Bot.rooms[room].connectfour[k];
return game && game.started && !game[game.turn].id === user;
});
if (!id) return Bot.roomReply(room, by, "Unable to find the game you meant to play in.");
const game = Bot.rooms[room].connectfour[id];
if (!game) return Bot.roomReply(room, by, "Not a valid ID.");
if (!game.started) return Bot.roomReply(room, by, 'OI, IT HASN\'T STARTED!');
if (!(game[game.turn].id === toID(by))) return;
let coords = args.join('').split(',');
if (coords.length !== 1) return Bot.roomReply(room, by, "I need one coordinate to play - why not click on the board instead?");
coords = coords.map(t => parseInt(toID(t)));
if (isNaN(coords[0])) return Bot.roomReply(room, by, "Invalid coordinate. ;-;");
game.drop(coords[0]).then(res => {
delete game.Y.isResigning;
delete game.R.isResigning;
clearGameTimer(game);
if (res) {
return runMoves('end', res, game);
}
if (game.board.find(col => col.length < game.rows)) {
const turn = game[game.turn].name;
gameTimer(game, turn);
return runMoves('move', null, game);
}
return runMoves('end', false, game);
}).catch(why => Bot.roomReply(room, by, why));
break;
}
case 'substitute': case 'sub': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].connectfour) return Bot.roomReply(room, by, 'This room does not have any Connect Four games.');
args.shift();
let id, cargs;
if (!Object.keys(Bot.rooms[room].connectfour).length) return Bot.roomReply(room, by, "No games are active.");
if (/^[^a-zA-Z]+$/.test(args[0])) id = toID(args.shift());
else if (Object.keys(Bot.rooms[room].connectfour).length === 1) id = Object.keys(Bot.rooms[room].connectfour)[0];
else {
cargs = args.join(' ').split(/\s*,\s*/);
if (cargs.length !== 2) return Bot.roomReply(room, by, "I NEED TWO NAMES GIVE ME TWO NAMES");
const id1 = toID(cargs[0]), id2 = toID(cargs[1]);
id = Object.keys(Bot.rooms[room].connectfour).find(k => {
const game = Bot.rooms[room].connectfour[k], ps = [game.Y.id, game.R.id];
return game && game.started && (ps.includes(id1) && !ps.includes(id2) || !ps.includes(id1) && ps.includes(id2));
});
}
cargs = args.join(' ').replace(/[<>]/g, '').split(/\s*,\s*/);
if (cargs.length !== 2) return Bot.roomReply(room, by, "I NEED TWO NAMES GIVE ME TWO NAMES");
if (!id) return Bot.roomReply(room, by, "Sorry, I couldn't find a valid game to sub.");
const game = Bot.rooms[room].connectfour[id];
if (!game.started) return Bot.roomReply(room, by, 'Excuse me?');
cargs = cargs.map(carg => carg.trim());
const users = cargs.map(carg => toID(carg));
if (users.includes(game.Y.id) && users.includes(game.R.id) || !users.includes(game.Y.id) && !users.includes(game.R.id)) return Bot.say(room, 'Those users? Something\'s wrong with those...');
if ([game.Y.id, game.R.id].includes(toID(by)) && !tools.hasPermission(by, 'coder')) return Bot.say(room, "Hah! Can't sub yourself out.");
let ex, add;
if (users.includes(game.Y.id)) {
if (users[0] == game.Y.id) {
Bot.say(room, `${game.Y.name} was subbed with ${cargs[1]}!`);
game.Y.id = users[1];
game.Y.name = cargs[1];
ex = users[0];
add = users[1];
} else {
Bot.say(room, `${game.Y.name} was subbed with ${cargs[0]}!`);
game.Y.id = users[0];
game.Y.name = cargs[0];
ex = users[1];
add = users[0];
}
} else {
if (users[0] == game.R.id) {
Bot.say(room, `${game.R.name} was subbed with ${cargs[1]}!`);
game.R.id = users[1];
game.R.name = cargs[1];
ex = users[0];
add = users[1];
} else {
Bot.say(room, `${game.R.name} was subbed with ${cargs[0]}!`);
game.R.id = users[0];
game.R.name = cargs[0];
ex = users[1];
add = users[0];
}
}
game.spectators.remove(add);
game.spectators.push(ex);
runMoves('move', null, game);
break;
}
case 'end': case 'e': {
if (!Bot.rooms[room].connectfour) return Bot.roomReply(room, by, 'This room does not have any Connect Four games.');
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
args.shift();
let id;
if (!Object.keys(Bot.rooms[room].connectfour).length) return Bot.roomReply(room, by, "No games are active.");
if (args.length && /^[^a-zA-Z]+$/.test(args.join(''))) id = toID(args.join(''));
else if (Object.keys(Bot.rooms[room].connectfour).length === 1) id = Object.keys(Bot.rooms[room].connectfour)[0];
else {
const cargs = args.join('').split(/(?:,|\s+v(?:er)?s(?:us)?\.?\s+)/).map(toID);
if (cargs.length !== 2) return Bot.roomReply(room, by, unxa);
id = Object.keys(Bot.rooms[room].connectfour).find(k => {
const game = Bot.rooms[room].connectfour[k];
if (cargs.includes(game.Y.id) && cargs.includes(game.R.id)) return true;
});
}
if (!id) return Bot.roomReply(room, by, "Unable to find the game you're talking about. :(");
const game = Bot.rooms[room].connectfour[id];
if (!game) return Bot.roomReply(room, by, "Invalid ID.");
if (!game.started) Bot.say(room, `/changeuhtml CONNECTFOUR-${id}, <hr/>Ended. :(<hr/>`);
clearGameTimer(game);
delete Bot.rooms[room].connectfour[id];
fs.unlink(`./data/BACKUPS/connectfour-${room}-${id}.json`, () => {});
return Bot.say(room, `Welp, ended Connect Four#${id}.`);
break;
}
case 'endf': case 'ef': {
if (!Bot.rooms[room].connectfour) return Bot.roomReply(room, by, 'This room does not have any Connect Four games.');
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
args.shift();
const [id, winner] = args.join('').split(',').map(toID);
if (!Object.keys(Bot.rooms[room].connectfour).length) return Bot.roomReply(room, by, "No games are active.");
if (!id) return Bot.roomReply(room, by, "Unable to find the game you're talking about. :(");
const game = Bot.rooms[room].connectfour[id];
if (!game) return Bot.roomReply(room, by, "Invalid ID.");
if (!game.started) {
clearGameTimer(game);
delete Bot.rooms[room][gameName][game.id];
fs.unlink(`./data/BACKUPS/connectfour-${room}-${id}.json`, () => {});
return Bot.say(room, `/changeuhtml CONNECTFOUR-${id}, <hr/>Ended. :(<hr/>`);
} else if (!winner || ![game.Y.id, game.R.id, 'none'].includes(winner)) return Bot.roomReply(room, by, `W-who won, again?`);
if (toID(by) === winner) return Bot.roomReply(room, by, 'Only I may be corrupt');
clearGameTimer(game);
runMoves('end', winner === game.Y.id ? 'Y' : 'R', game);
break;
}
case 'backups': case 'bu': case 'stashed': case 'b': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, "Access denied.");
if (isPM) return Bot.roomReply(room, by, `Please use this in the room. Please. PLEASE`);
fs.readdir('./data/BACKUPS', (err, files) => {
if (err) {
Bot.say(room, err);
return Bot.log(err);
}
const games = files.filter(file => file.startsWith(`connectfour-${room}-`)).map(file => file.slice(0, -4)).map(file => file.replace(/[^0-9]/g, ''));
if (games.length) {
Bot.say(room, `/adduhtml CONNECTFOURBACKUPS, <details><summary>Game Backups</summary><hr />${games.map(game => {
const info = require(`../../data/BACKUPS/connectfour-${room}-${game}.json`);
return `<button name="send" value="/botmsg ${Bot.status.nickName},${prefix}connectfour ${room} restore ${game}">${info.Y.name} vs ${info.R.name}</button>`;
}).join('<br />')}</details>`);
} else Bot.say(room, "No backups found.");
});
break;
}
case 'restore': case 'resume': case 'r': {
args.shift();
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, "Access denied.");
const id = parseInt(args.join(''));
if (!id) return Bot.say(room, "Invalid ID.");
if (Bot.rooms[room].connectfour?.[id]) return Bot.roomReply(room, by, "Sorry, that game is already in progress!");
fs.readFile(`./data/BACKUPS/connectfour-${room}-${id}.json`, 'utf8', (err, file) => {
if (err) return Bot.say(room, "Sorry, couldn't find that game!");
if (!Bot.rooms[room].connectfour) Bot.rooms[room].connectfour = {};
Bot.rooms[room].connectfour[id] = GAMES.create('connectfour', id, {}, room, JSON.parse(file));
Bot.say(room, "Game has been restored!");
const game = Bot.rooms[room].connectfour[id];
game.spectators.forEach(spect => Bot.say(room, `/sendhtmlpage ${spect}, Connect Four + ${room} + ${id}, <center><h1>${game[game.turn].name}'s Turn (${game.turn})</h1>${game.boardHTML()}</center>`));
Bot.say(room, `/sendhtmlpage ${game.Y.id}, Connect Four + ${room} + ${id}, ${game.turn === "Y" ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
Bot.say(room, `/sendhtmlpage ${game.R.id}, Connect Four + ${room} + ${id}, ${game.turn === "R" ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
});
return;
break;
}
case 'menu': case 'm': case 'list': case 'l': case 'players': {
const connectfour = Bot.rooms[room].connectfour;
if (!connectfour || !Object.keys(connectfour).length) {
if (tools.hasPermission(by, 'gamma', room) && !isPM) return Bot.say(room, "Sorry, no games found.");
return Bot.roomReply(room, by, "Sorry, no games found.");
}
const html = `<hr />${Object.keys(connectfour).map(id => {
const game = connectfour[id];
return `${game.Y.name ? tools.colourize(game.Y.name) : `<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}connectfour ${room} join ${id} Yellow">Yellow</button>`} vs ${game.R.name ? tools.colourize(game.R.name) : `<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}connectfour ${room} join ${id} Red">Red</button>`} ${game.started ? `<button name="send" value ="/msg ${Bot.status.nickName}, ${prefix}connectfour ${room} spectate ${id}">Watch</button> ` : ''}(#${id})`;
}).join('<br />')}<hr />`;
const staffHTML = `<hr />${Object.keys(connectfour).map(id => {
const game = connectfour[id];
return `${game.Y.name ? tools.colourize(game.Y.name) : `<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}connectfour ${room} join ${id} Yellow">Yellow</button>`} vs ${game.R.name ? tools.colourize(game.R.name) : `<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}connectfour ${room} join ${id} Red">Red</button>`} ${game.started ? `<button name="send" value ="/msg ${Bot.status.nickName}, ${prefix}connectfour ${room} spectate ${id}">Watch</button> ` : ''}<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}connectfour ${room} end ${id}">End</button> <button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}connectfour ${room} stash ${id}">Stash</button>(#${id})`;
}).join('<br />')}<hr />`;
if (isPM === 'export') return [html, staffHTML];
if (tools.hasPermission(by, 'gamma', room) && !isPM) {
Bot.say(room, `/adduhtml CONNECTFOURMENU,${html}`);
Bot.say(room, `/changerankuhtml +, CONNECTFOURMENU, ${staffHTML}`);
} else Bot.say(room, `/sendprivatehtmlbox ${by}, ${html}`);
break;
}
case 'resign': case 'forfeit': case 'f': case 'ff': case 'ihavebeenpwned': case 'bully': {
if (!Bot.rooms[room].connectfour) return Bot.roomReply(room, by, 'There isn\'t an active Connect Four game in this room.');
args.shift();
let id, user = toID(by);
if (args.length) id = toID(args.join(''));
else if (Object.keys(Bot.rooms[room].connectfour).length === 1) id = Object.keys(Bot.rooms[room].connectfour)[0];
else id = Object.keys(Bot.rooms[room].connectfour).find(k => {
const game = Bot.rooms[room].connectfour[k];
return game && game.started && [game.Y.id, game.R.id].includes(user);
});
if (!id) return Bot.roomReply(room, by, "Unable to find the game you meant to play in.");
const game = Bot.rooms[room].connectfour[id];
if (!game) return Bot.roomReply(room, by, "Not a valid ID.");
if (!game.started) return Bot.roomReply(room, by, '>resigning before it starts');
if (![game.Y.id, game.R.id].includes(user)) return Bot.roomReply(room, by, "Only a player can resign.");
const side = game.Y.id === user ? "Y" : "R";
if (!game[side].isResigning) {
Bot.roomReply(room, by, 'Are you sure you want to resign? If you are, use this command again.');
return game[side].isResigning = true;
}
clearGameTimer(game);
runMoves('resign', side, game);
break;
}
case 'spectate': case 's': case 'watch': case 'w': {
if (!Bot.rooms[room].connectfour) return Bot.roomReply(room, by, 'This room does not have any Connect Four games.');
args.shift();
let id;
if (args.length && /^[^a-zA-Z]+$/.test(args.join(''))) id = toID(args.join(''));
else if (Object.keys(Bot.rooms[room].connectfour).length === 1) id = Object.keys(Bot.rooms[room].connectfour)[0];
else if (Object.values(Bot.rooms[room].connectfour).filter(game => game.started).length === 1) id = Object.values(Bot.rooms[room].connectfour).filter(game => game.started)[0].id;
else {
const cargs = args.join('').split(/(?:,|\s+v(?:er)?s(?:us)?\.?\s+)/).map(toID);
if (cargs.length !== 2) return Bot.roomReply(room, by, "Sorry, specify the players again?");
id = Object.keys(Bot.rooms[room].connectfour).find(k => {
const game = Bot.rooms[room].connectfour[k];
if (cargs.includes(game.Y.id) && cargs.includes(game.R.id) && !game.spectators.includes(toID(by))) return true;
});
}
const game = Bot.rooms[room].connectfour[id];
if (!game) return Bot.roomReply(room, by, "Sorry, no Connect Four game here to spectate.");
if (!game.started) Bot.roomReply(room, by, "Oki, I'll send you the board when it starts.");
const user = toID(by);
if ([game.Y.id, game.R.id].includes(user)) return Bot.roomReply(room, by, "Imagine spectating your own game.");
if (!game.spectators.includes(user)) game.spectators.push(user);
Bot.say(room, `/sendhtmlpage ${by}, Connect Four + ${room} + ${id}, <center><h1>${game[game.turn].name}'s Turn (${game.turn})</h1>${game.boardHTML()}</center>`);
return Bot.roomReply(room, by, `You are now spectating the Connect Four match between ${game.Y.name} and ${game.R.name}!`);
break;
}
case 'unspectate': case 'us': case 'unwatch': case 'uw': case 'zestoflifeisstinky': {
if (!Bot.rooms[room].connectfour) return Bot.roomReply(room, by, 'This room does not have any Connect Four games.');
args.shift();
let id;
if (args.length && /^[^a-zA-Z]+$/.test(args.join(''))) id = toID(args.join(''));
else if (Object.values(Bot.rooms[room].connectfour).filter(game => game.spectators.includes(toID(by))).length === 1) id = Object.values(Bot.rooms[room].connectfour).filter(game => game.spectators.includes(toID(by)))[0].id;
else {
const cargs = args.join('').split(/(?:,|\s+v(?:er)?s(?:us)?\.?\s+)/).map(toID);
if (cargs.length !== 2) return Bot.roomReply(room, by, "Sorry, didn't get the game you meant.");
id = Object.keys(Bot.rooms[room].connectfour).find(k => {
const game = Bot.rooms[room].connectfour[k];
if (cargs.includes(game.Y.id) && cargs.includes(game.R.id) && game.spectators.includes(toID(by))) return true;
});
}
const game = Bot.rooms[room].connectfour[id];
if (!game) return Bot.roomReply(room, by, "Sorry, no Connect Four game here to unspectate.");
if (!game.started) return Bot.roomReply(room, by, "AYAYAYA - no.");
const user = toID(by);
if ([game.Y.id, game.R.id].includes(user)) return Bot.roomReply(room, by, "Imagine unspectating your own game.");
if (!game.spectators.includes(user)) return Bot.roomReply(room, by, `You aren't spectating! If you want to, use \`\`${prefix}connectfour spectate\`\` instead!`);
game.spectators.remove(user);
return Bot.roomReply(room, by, `You are no longer spectating the Connect Four match between ${game.Y.name} and ${game.R.name}.`);
break;
}
case 'rejoin': case 'rj': {
const games = Bot.rooms[room].connectfour;
if (!games) return Bot.roomReply(room, by, "Sorry, no Connect Four game here to spectate.");
const user = toID(by);
const ids = Object.keys(games).filter(key => [games[key].Y.id, games[key].R.id, ...games[key].spectators].includes(user));
if (!ids.length) return Bot.roomReply(room, by, "Couldn't find any games for you to rejoin.");
ids.forEach(id => {
let game = games[id], side;
if (game.Y.id === user) side = "Y";
if (game.R.id === user) side = "R";
if (!side && !game.spectators.includes(toID(by))) return Bot.roomReply(room, by, `You don't look like a player / spectator - try ${prefix}connectfour spectate ${id}... ;-;`);
if (game.spectators.includes(user)) Bot.say(room, `/sendhtmlpage ${by}, Connect Four + ${room} + ${id}, <center><h1>${game[game.turn].name}'s Turn (${game.turn})</h1>${game.boardHTML()}</center>`);
else Bot.say(room, `/sendhtmlpage ${user}, Connect Four + ${room} + ${id}, ${game.turn === side ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
});
break;
}
case 'stash': case 'store': case 'freeze': case 'hold': case 'h': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].connectfour) return Bot.roomReply(room, by, 'This room does not have any Connect Four games.');
args.shift();
let id;
if (!Object.keys(Bot.rooms[room].connectfour).length) return Bot.roomReply(room, by, "No games are active.");
if (args.length && /^[^a-zA-Z]+$/.test(args.join(''))) id = toID(args.join(''));
else if (Object.keys(Bot.rooms[room].connectfour).length === 1) id = Object.keys(Bot.rooms[room].connectfour)[0];
else {
const cargs = args.join('').split(/(?:,|\s+v(?:er)?s(?:us)?\.?\s+)/).map(toID);
if (cargs.length !== 2) return Bot.roomReply(room, by, unxa);
id = Object.keys(Bot.rooms[room].connectfour).find(k => {
const game = Bot.rooms[room].connectfour[k];
if (cargs.includes(game.Y.id) && cargs.includes(game.R.id)) return true;
});
}
if (!id) return Bot.roomReply(room, by, "Unable to find the game you're talking about. :(");
const game = Bot.rooms[room].connectfour[id];
if (!game) return Bot.roomReply(room, by, "Invalid ID.");
Bot.say(room, `The Connect Four match between ${game.Y.name || '(no one)'} and ${game.R.name || '(no one)'} has been put on hold!`);
delete Bot.rooms[room].connectfour[id];
break;
}
default: {
Bot.roomReply(room, by, `That, uhh, doesn't seem to be something I recognize?`);
break;
}
}
}
};
<file_sep>/discord/qfar.js
const PZ = require('../data/PUZZLES/index.js');
module.exports = {
help: `Displays a list of usable commands.`,
admin: true,
guildOnly: PZ.guildID,
commandFunction: function (args, message, Bot) {
delete require.cache[require.resolve('../data/PUZZLES/index.js')];
const PZ = require('../data/PUZZLES/index.js');
message.channel.send("The Puzzles module has been reloaded.");
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/snom.js
module.exports = {
cooldown: 10000,
help: `SNOM!`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `/adduhtml SNOM,<CENTER><IMG src="https://media.discordapp.net/attachments/652695616610238464/656154115080060938/1573694833723.png" height="100" width="100"></CENTER>`);
}
};
<file_sep>/pmcommands/endraid.js
module.exports = {
noDisplay: true,
help: `End a PoGo raid`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
const room = 'pokemongo';
if (!Bot.rooms[room]) return Bot.pm(by, `Uhh I'm not in Pokemon Go`);
const user = toID(by);
if (!Bot.rooms[room].users.find(u => toID(u) === user)) return Bot.pm(by, `<<pokemongo>>`);
if (!tools.hasPermission(by, 'gamma', room)) return Bot.pm(by, 'Access DENIED!');
const raids = Bot.rooms[room].raids || {};
if (!Object.keys(raids).length) return Bot.pm(by, "No raids are active, whoops");
const host = toID(args.join(''));
if (!raids.hasOwnProperty(host)) return Bot.pm(by, `B-but who's hosting?`);
const raid = raids[host];
clearInterval(raid.timer);
clearInterval(raid.warningTimer);
clearInterval(raid.fiveTimer);
clearInterval(raid.hostTimer);
Bot.say(room, `/adduhtml RAIDHTML${host}, ${raid.hostName}'s ${raid.pokemon} raid has been ended by ${by.substr(1)}`);
delete Bot.rooms[room].raids[host];
}
};
<file_sep>/data/GAMES/connectfour.js
class ConnectFour {
constructor (id, info, room, restore) {
this.id = id;
info.rows = parseInt(info.rows);
if (info.rows > 10 || info.rows < 5 || !info.rows) info.rows = 6;
info.cols = parseInt(info.cols);
if (info.cols > 10 || info.cols < 5 || !info.cols) info.cols = 7;
this.rows = info.rows;
this.cols = info.cols;
this.turn = 'Y';
this.room = room;
this.Y = {
id: '',
name: ''
};
this.R = {
id: '',
name: ''
};
this.board = Array.from({ length: this.cols }).map(() => []);
this.spectators = [];
this.moves = [];
this.started = false;
if (restore) Object.assign(this, restore);
}
nextTurn (last) {
const win = this.isWon(this.board, last);
if (win) return win;
this.turn = this.turn === 'Y' ? 'R' : 'Y';
return false;
}
drop (col) {
return new Promise((resolve, reject) => {
col = parseInt(col);
if (!(col >= 0 && col < this.cols)) return reject('Column does not exist');
if (this.board[col].length === this.rows) return reject('Column is full');
this.board[col].push(this.turn);
this.moves.push(col);
return resolve(this.nextTurn(col));
});
}
isWon (board, col) {
if (!board) board = this.board;
const row = this.board[col].length - 1;
let j;
// Vertical
if (row >= 3) {
j = row - 3;
if ([0, 1, 2, 3].every(k => board[col][j + k] === this.turn)) return this.turn;
}
// Horizontal
for (j = Math.max(col - 3, 0); j <= Math.min(this.cols - 4, col); j++) {
if ([0, 1, 2, 3].every(k => board[j + k][row] === this.turn)) return this.turn;
}
// Ascending
j = [col - 3, row - 3];
while (j[0] < 0 || j[1] < 0) {
j[0]++;
j[1]++;
}
while (j[0] <= Math.min(this.cols - 4, col) && j[1] <= Math.min(this.rows - 4, row)) {
if ([0, 1, 2, 3].every(k => board[j[0] + k][j[1] + k] === this.turn)) return this.turn;
j[0]++;
j[1]++;
}
// Descending
j = [col - 3, row + 3];
while (j[0] < 0 || j[1] >= this.rows) {
j[0]++;
j[1]--;
}
while (j[0] <= Math.min(this.cols - 4, col) && j[1] >= Math.max(row - 3, 3)) {
if ([0, 1, 2, 3].every(k => board[j[0] + k][j[1] - k] === this.turn)) return this.turn;
j[0]++;
j[1]--;
}
return false;
}
boardHTML (player, passed) {
const colours = { 'Y': "#ffff00", 'R': "#e60000", 'E': "#111111", 'bg': "#0080ff" };
const board = Array.from({ length: this.cols }).map((col, x) => {
return Array.from({ length: this.rows }).map((_, y) => this.board[x][y] || 'E');
});
board.forEach(col => col.reverse());
// eslint-disable-next-line max-len
const html = `<center style="max-height: 400px; overflow-y: scroll;"><table style="border:none;background:${colours.bg};border-radius:5%;">${board[0].map((col, i) => board.map(row => row[i])).map((row) => `<tr>${row.map((bulb, y) => `<td>${player ? `<button name="send" value="/msgroom ${this.room},/botmsg ${Bot.status.nickName},${prefix}connectfour ${this.room} click ${this.id} ${y}" style="background:none;border:none;padding:0">` : ''}<div style="height:${passed ? '15' : '35'}px;width:${passed ? '15' : '35'}px;background-image:radial-gradient(${colours[bulb]} 50%,#333333);border-radius:50%;margin:${passed ? '1.5' : '3'}px"></div>${player ? '</button>' : ''}</td>`).join('')}</tr>`).join('')}</table></center>`;
return html;
}
}
module.exports = ConnectFour;
<file_sep>/commands/boardgames/chesscv.js
/* eslint-disable no-unreachable */
module.exports = {
cooldown: 10000,
help: `Converts a given chessboard into FEN.`,
permissions: 'alpha',
commandFunction: function (Bot, room, time, by, args, client) {
let imgLink = args.join(' ').match(/https?:\/\/\S*/);
return Bot.say(room, `Sorry, but this command has been yeeted.`);
if (!imgLink) return Bot.say(room, `No image link found.`);
imgLink = imgLink[0];
axios.get(imgLink).then(res => {
if (!res.headers['content-type'].startsWith('image/')) {
return Bot.say(room, `Could not detect a valid image in ${imgLink}`);
}
const { exec } = require('child_process');
exec(`/usr/bin/python3 /home/ubuntu/PartBot/data/CHESSCV/tensorflow_chessbot.py --url ${imgLink}`, {
cwd: '/home/ubuntu/PartBot/data/CHESSCV',
shell: false
}, (error, stdout, stderr) => {
const info = stdout;
const fen = info.match(/\nPredicted FEN:\n([^\n]*)\n/);
let certain = info.match(/Final Certainty: [\d\.]+%/);
if (!certain || (certain = parseInt(certain[1])) < 90) return Bot.say(room, `Unable to analyze image.`);
if (!fen) return Bot.say(room, `Invalid FEN`);
Bot.say(room, `Generated FEN: ${fen[1]}`);
});
}).catch((err) => {
Bot.say(room, `Could not detect a valid image in ${imgLink}`);
});
}
};
/*
---
Visualize tiles link:
http://tetration.xyz/tensorflow_chessbot/overlay_chessboard.html
?1,0,481,480,https%3A%2F%2Fcdn.discordapp.com%2Fattachments%2F738350604510036050%2F825827681018576896%2Funknown.png
---
--- Prediction on url https://cdn.discordapp.com/attachments/738350604510036050/825827681018576896/unknown.png ---
Loading model 'saved_models/frozen_graph.pb'
Model restored.
Closing session.
Per-tile certainty:
[[1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1. 1. 1.]]
Certainty range [0.999995 - 1], Avg: 0.999998
---
Predicted FEN:
8/3R1N1k/3Bp1p1/7p/4bpP1/5Q2/1K6/6q1 w - - 0 1
Final Certainty: 100.0%
*/
<file_sep>/pmcommands/namecolour.js
module.exports = {
help: `Displays a user's namecolour.`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
const HSL = tools.HSL(args.join('') || by);
// eslint-disable-next-line max-len
let html = `<strong style="color: hsl(${HSL.hsl[0]}, ${HSL.hsl[1]}%, ${HSL.hsl[2]}%);">${args.join(' ') || by.substr(1)}</strong> [Hex: ${tools.HSLtoHEX(...HSL.hsl)}, RGB: ${tools.HSLtoRGB(...HSL.hsl).join(', ')}, HSL: ${HSL.hsl[0]}, ${HSL.hsl[1]}%, ${HSL.hsl[2]}%]`;
// eslint-disable-next-line max-len
if (HSL.base) html += ` (${tools.colourize(HSL.source)})<br />Original: <strong style="color: hsl(${HSL.base.hsl[0]}, ${HSL.base.hsl[1]}%, ${HSL.base.hsl[2]}%);">${HSL.base.source}</strong> [Hex: ${tools.HSLtoHEX(...HSL.base.hsl)}, RGB: ${tools.HSLtoRGB(...HSL.base.hsl).join(', ')}, HSL: ${HSL.base.hsl[0]}, ${HSL.base.hsl[1]}%, ${HSL.base.hsl[2]}%]`;
Bot.sendHTML(by, html);
}
};
<file_sep>/data/GAMES/index.js
module.exports = {
_games: {},
list () {
return [
'battleship',
'chainreaction',
'chess',
'connectfour',
'lightsout',
'linesofaction',
'mastermind',
'othello',
'scrabble'
];
},
init () {
const self = this;
return Promise.all(self.list().map(game => {
return new Promise((resolve, reject) => {
try {
self._games[game] = require(`./${game}.js`);
resolve();
} catch (e) {
reject(e);
}
});
}));
},
reload () {
const self = this;
return new Promise((resolve, reject) => {
try {
self.list().forEach(game => delete require.cache[require.resolve(`./${game}.js`)]);
delete self._games;
self._games = {};
self.init();
resolve();
} catch (e) {
reject(e);
}
});
},
get (game) {
game = toID(game);
if (!this.list().includes(game)) return null;
return this._games[game];
},
create (game, ...opts) {
game = this.get(game);
if (!game) return null;
return new game(...opts);
}
};
<file_sep>/discord/kill.js
module.exports = {
help: `Exits the process.`,
admin: true,
pm: true,
commandFunction: function (args, message, Bot) {
message.channel.send('o/').then(() => process.exit());
}
};
<file_sep>/pmcommands/trickhouse.js
module.exports = {
help: `Syntax: ${prefix}trickhouse (challenger), (difficulty - 1/2/3), (replay / post-match Elo)`,
permissions: 'none',
commandFunction: async function (Bot, by, args, client) {
const userID = toID(by);
if (
!tools.hasPermission(by, 'trickhouse', 'beta') ||
Bot.rooms.trickhouse?.users.find(u => toID(u) === userID)?.startsWith(' ')
) return Bot.pm(by, `Access denied.`);
const cargs = args.join(' ').split(',');
if (cargs.length < 3 || cargs.length > 4) return Bot.pm(by, unxa);
const challenger = cargs.shift().trim();
let difficulty = toID(cargs.shift());
const difficulties = [null, 'easy', 'medium', 'hard'];
if (difficulties.includes(difficulty)) difficulty = difficulties.indexOf(difficulty);
difficulty = ~~difficulty;
if (difficulty > 3 || difficulty <= 0) return Bot.pm(by, `Invalid difficulty.`);
const replay = cargs.shift().trim();
let elo;
if (~~replay) elo = ~~replay;
else {
function getRatings (a, won, b) {
function getKFactor (elo, win) {
if (elo >= 1600) return 32;
if (elo >= 1300) return 40;
if (elo >= 1100) return 50;
const scale = (1099 - elo) / 99;
if (win) return 50 + 30 * scale;
else return 50 - 30 * scale;
}
function getExpected (a, b) {
return 1 / (1 + Math.pow(10, (b - a) / 400));
}
const expectedA = getExpected(a, b);
const expectedB = getExpected(b, a);
const finalA = Math.round(a + getKFactor(a, won) * (+won - expectedA));
const finalB = Math.round(b + getKFactor(b, !won) * (+!won - expectedB));
return [finalA, finalB];
}
async function parseLink (url) {
if (!url.startsWith('https://replay.pokemonshowdown.com/gen')) throw new Error('Link must be a Showdown replay');
const link = url.endsWith('.log') ? url : url + '.log';
const res = await axios.get(link);
const lines = res.data.split('\n');
const players = {};
let self, other;
let rated;
lines.forEach(line => {
const args = line.split('|');
args.shift();
switch (args[0]) {
case 'player': {
const id = toID(args[2]);
if (!args[4]) break;
players[id] = {
name: args[2],
id,
elo: ~~args[4],
pos: args[1]
};
break;
}
case 'rated': {
rated = true;
break;
}
case 'win': {
const win = toID(args[1]);
const winner = players[win];
if (!winner) throw new Error(`You suck (couldn't find the winner from the players)`);
const loser = Object.values(players).find(p => p.id !== win);
winner.win = true;
loser.win = false;
break;
}
}
});
if (!rated) throw new Error('Battle was unrated');
const elos = getRatings(winner.elo, true, loser.elo);
return elos;
}
try {
[elo] = await parseLink(replay, toID(challenger));
} catch (err) {
Bot.pm(by, err.message);
return Bot.log(err);
}
}
const points = Math.round(((elo - 1000) ** 2 / 500 + 300) * difficulty);
try {
await tools.addPoints(0, challenger, points, 'trickhouse');
const Room = Bot.rooms.trickhouse;
const id = cargs.length ? cargs.shift() : null;
if (id && Room?.vers?.[id]) {
const chall = Room.vers[id];
Bot.say('trickhouse', `/changerankuhtml ${chall.challenge}-${chall.challenger}-${id},Approved`);
delete Rooms.vers[id];
}
const pointsStr = `${points} point${points === 1 ? '' : 's'}`;
Bot.pm(by, `Awarded ${pointsStr} to ${challenger}.`);
const msg = `You were awarded ${pointsStr} in Trick House! Use \`\`${prefix}leaderboard trickhouse\`\` to check.`;
Bot.pm(challenger, msg);
} catch (e) {
Bot.log(e);
Bot.pm(by, `Yo uhh PartMan sucks (${e.message})`);
}
}
};
<file_sep>/pmcommands/1v1tc.js
module.exports = {
help: `Recreates the 1v1TC GC.`,
noDisplay: true,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
if (Bot.rooms[tcroom]) return Bot.say(tcroom, `/invite ${by}`);
if (!Bot.baseAuth[tcroom][toID(by)] || Bot.baseAuth[tcroom][toID(by)] < 4) return Bot.pm(by, 'Access denied.');
Bot.say('botdevelopment', '/makegroupchat 1v1TC');
Bot.say(tcroom, `/invite ${by}`);
const typeChan = client.channels.cache.get('542524011066949633');
typeChan.send(`${by.substr(1)} brought the GC online! https://play.pokemonshowdown.com/groupchat-partbot-1v1tc`);
const invitees = [].concat(...Object.keys(Bot.baseAuth[tcroom]));
if (Bot.tcInvitees) invitees.concat(Bot.tcInvitees);
function inviteTimer (i) {
if (i >= invitees.length) return;
Bot.say(tcroom, `/forceroomvoice ${invitees[i]}\n/invite ${invitees[i]}`);
setTimeout(inviteTimer, 1000, i + 1);
}
inviteTimer(0);
return Bot.say(tcroom, 'UwU');
}
};
<file_sep>/pmcommands/rttts.js
/* eslint-disable no-unreachable */
module.exports = {
help: `Hunt Board Games roomauth!`,
noDisplay: true,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
return Bot.pm(by, `B-but UGO is over!`);
const userID = toID(by);
if (!tools.hasPermission(by, 'boardgames', 'gamma') || Bot.rooms.boardgames?.users.find(u => toID(u) === userID)?.test(/^ /)) {
return Bot.pm(by, `Access denied - please ask the auth member to PM me \`\`${prefix}rttt ${toID(by)}\`\``);
}
const cargs = args.join(' ').split(',').map(term => term.trim());
if (cargs.length !== 2) return Bot.pm(by, unxa);
const targetID = toID(cargs[0]);
const target = Bot.rooms.boardgames?.users.find(u => toID(u) === targetID)?.replace(/@!$/, '').substr(1);
if (!target) return Bot.pm(by, `Unable to find the target in Board Games!`);
const user = by.substr(1).replace(/@!$/, '');
const players = {
'X': cargs[1].toUpperCase() === 'X' ? target : user,
'O': cargs[1].toUpperCase() === 'O' ? target : user
};
const moves = Array.from({ length: 9 }).map((_, i) => i).shuffle();
const board = Array.from({ length: 9 }).fill(null);
const HTMLs = [];
let turn = true;
let result = 'O';
while (moves.length) {
const move = moves.shift();
const isTurn = 'XO'[~~(turn = !turn)];
board[move] = isTurn;
tempBoard = [board.slice(0, 3), board.slice(3, 6), board.slice(6, 9)];
// eslint-disable-next-line max-len
HTMLs.push(`<center><table style="border-collapse:collapse;border:2px solid;margin:30px">${tempBoard.map(row => `<tr style="height:30px">${row.map(cell => `<td style="border:2px solid;width:30px;text-align:center;line-height:30px">${cell || ' '}</td>`).join('')}</tr>`).join('')}</table></center>`);
function isWon () {
const squares = { X: [], O: [] };
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (tempBoard[i][j]) squares[tempBoard[i][j]].push([i, j]);
}
}
for (let i = 0; i < 3; i++) {
if (squares.X.filter(term => term[0] === i).length === 3) return 'X';
if (squares.X.filter(term => term[1] === i).length === 3) return 'X';
if (squares.O.filter(term => term[0] === i).length === 3) return 'O';
if (squares.O.filter(term => term[1] === i).length === 3) return 'O';
}
if (tempBoard[0][0] === tempBoard[1][1] && tempBoard[1][1] === tempBoard[2][2]) return tempBoard[0][0];
if (tempBoard[2][0] === tempBoard[1][1] && tempBoard[1][1] === tempBoard[0][2]) return tempBoard[1][1];
return 0;
}
const win = isWon();
if (win) {
result = win;
break;
}
}
const winner = players[result];
if (winner === target) result = ' won against ';
else if (winner === user) result = ' lost against ';
// eslint-disable-next-line max-len
HTMLs[HTMLs.length - 1] = `<center><h1>${target}${result}${user}</h1><br/>` + HTMLs[HTMLs.length - 1] + (winner === target ? `<form data-submitsend="/msgroom ugo,/pm UGO,;authhunt ${target}, Board Games"><input type="submit" value="Click to award points!" name="Click to award points!"></form>` : '') + '</center>';
// declare 'result'
function timer () {
if (!HTMLs.length) return Bot.say('ugo', `/modnote [boardgamesauthhunt] [${target}]${result}[${user}]`);
const HTML = HTMLs.shift();
Bot.say('boardgames', `/sendhtmlpage ${target}, rttt${target}${user}, ${HTML.replace(/<form.*?form>/, '')}`);
Bot.say('boardgames', `/sendhtmlpage ${user}, rttt${target}${user}, ${HTML}`);
setTimeout(timer, 3000);
}
timer();
}
};
<file_sep>/commands/pokemongo/setshiny.js
module.exports = {
cooldown: 0,
help: `Updates PartBot's internal shiny list`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client, isPM) {
return Bot.roomReply(room, by, `Please check Discord onegai`);
// eslint-disable-next-line no-unreachable
const inStr = args.join('');
if (!inStr) return Bot.roomReply(room, by, 'Mention the Pokémon names and whether they need to be set to true/false!');
const mons = inStr.split(',').map(toID);
const tfi = mons.findIndex(mon => ['true', 'false'].includes(mon));
if (tfi < 0) return Bot.roomReply(room, by, `Mention true/false, please!`);
const tf = mons[tfi] === 'true';
mons.splice(tfi, 1);
if (!mons.length) return Bot.roomReply(room, by, `You also need to mention the Pokémon in question!`);
const pkmn = mons.map(mon => tools.queryGO(mon));
if (pkmn.find(t => !t || t.type !== 'pokemon')) return Bot.roomReply('Invalid Pokémon');
const ids = pkmn.map(mon => toID(mon.info.name));
ids.forEach(mon => data.godex[mon].shiny = tf);
fs.writeFile('./data/DATA/godex.json', JSON.stringify(data.godex, null, '\t'), err => {
if (err) {
Bot.log(err);
Bot.roomReply(room, by, `Error: ${err.message}`);
}
Bot.roomReply(`Updated! ${tools.listify(pkmn.map(mon => mon.info.name))} are now designated as ${tf ? '' : 'non-'}shiny.`);
Bot.hotpatch('godex', by);
});
}
};
<file_sep>/discord/nerdify.js
module.exports = {
help: `Adds the Nerd role.`,
guildOnly: "750048485721505852",
commandFunction: function (args, message, Bot) {
if (!message.member.roles.cache.find(r => r.id === "771591913332539414")) {
return message.channel.send("Permission denied.").then(msg => message.delete() && msg.delete({ timeout: 3000 }));
}
if (!message.mentions.users.size) {
return message.channel.send("Who?").then(msg => message.delete() && msg.delete({ timeout: 3000 }));
}
const newUser = message.guild.members.cache.find(mem => mem.id === message.mentions.users.first().id);
Bot.log(message.author.username + ' > ' + message.mentions.users.first().username);
newUser.roles.add(message.guild.roles.cache.get("771591913332539414")).then(() => {
message.delete({ timeout: 100 }).then(() => {
message.channel.send("Added.").then(msg => msg.delete({ timeout: 3000 }));
});
}).catch(Bot.log);
}
};
<file_sep>/commands/global/reload.js
module.exports = {
cooldown: 1,
help: `Reloads a command. Syntax: ${prefix}reload (command) (room [if applicable])`,
permissions: 'coder',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args[0]) return Bot.say(room, unxa);
const commandName = tools.commandAlias(toID(args.shift()));
let comRoom = room;
if (args[0]) comRoom = toID(args.join(''));
fs.readdir('./commands/global', (e, gcommands) => {
if (e) return console.log(e);
if (gcommands.includes(commandName + '.js')) {
delete require.cache[require.resolve('./' + commandName + '.js')];
Bot.log(by.substr(1) + ' reloaded the ' + commandName + ' command.');
return Bot.say(room, 'The ' + commandName + ' command has been reloaded.');
}
fs.readdir('./commands/' + comRoom, (e, files) => {
if (e) return Bot.say(room, 'It doesn\'t look like that command exists.');
if (files.includes(commandName + '.js')) {
delete require.cache[require.resolve('../' + comRoom + '/' + commandName + '.js')];
Bot.log(by.substr(1) + ' reloaded the ' + commandName + ' command.');
return Bot.say(room, 'The ' + commandName + ' command has been reloaded.');
}
return Bot.say(room, 'It doesn\'t look like that command exists.');
});
});
}
};
<file_sep>/pmcommands/1v1mnm.js
module.exports = {
help: `Recreates the 1v1 MnM GC.`,
noDisplay: true,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
if (Bot.rooms['groupchat-partbot-1v1mnm']) return Bot.say('groupchat-partbot-1v1mnm', `/invite ${by}`);
if (!Bot.baseAuth['groupchat-partbot-1v1mnm'][toID(by)] || Bot.baseAuth['groupchat-partbot-1v1mnm'][toID(by)] < 4) {
return Bot.pm(by, 'Access denied.');
}
Bot.say('botdevelopment', '/makegroupchat 1v1 MnM');
Bot.say('groupchat-partbot-1v1mnm', `/invite ${by}`);
const mnmChan = client.channels.cache.get('713969903979331655');
mnmChan.send(`${by.substr(1)} brought the GC online! https://play.pokemonshowdown.com/groupchat-partbot-1v1mnm`);
const invitees = [].concat(...Object.keys(Bot.baseAuth['groupchat-partbot-1v1mnm']));
if (Bot.tcInvitees) invitees.concat(Bot.tcInvitees);
function inviteTimer (i) {
if (i >= invitees.length) return;
Bot.say('groupchat-partbot-1v1mnm', `/forceroomvoice ${invitees[i]}\n/invite ${invitees[i]}`);
setTimeout(inviteTimer, 1000, i + 1);
}
if (!args.length) inviteTimer(0);
return Bot.say('groupchat-partbot-1v1mnm', 'UwU');
}
};
<file_sep>/data/VR/TC7/bug.js
exports.bug = {
sp: [],
s: ["Forretress", "Pinsir-Mega"],
sm: ["Scizor-Mega", "Heracross", "Dwebble"],
ap: ["Volcarona"],
a: ["Heracross-Mega", "Durant"],
am: ["Armaldo", "Vikavolt", "Buzzwole"],
bp: ["Shuckle", "Scolipede"],
b: ["Yanma"],
bm: ["Araquanid"],
cp: [],
c: ["Pheromosa", "Escavalier"],
cm: ["Venomoth", "Yanmega"],
d: ["Beedrill-Mega", "Ribombee", "Golisopod", "Vivillon"],
e: ["Ninjask", "Galvantula", "Accelgor", "Shedinja"],
unt: [],
bans: ["Crustle", "Genesect"]
};
<file_sep>/data/tools.js
/************************
* Utility *
************************/
exports.quoteParse = function (quote, smogon, utg) {
const ranks = ['★', '☆', '^', '⛵', 'ᗢ', '+', '%', '§', '@', '*', '#', '&', '~', '$', '-'];
const chatRegex = new RegExp(`^(\\[(?:\\d{2}:){1,2}\\d{2}\\] |)([${ranks.join('')}]?)([a-zA-Z0-9][^:]{0,25}?): (.*)$`);
const meRegex = new RegExp(`^(\\[(?:\\d{2}:){1,2}\\d{2}\\] |)• ([${ranks.join('')}]?)(\\[[a-zA-Z0-9][^\\]]{0,25}\\]) (.*)$`);
const jnlRegex = /^(?:.*? (?:joined|left)(?:; )?){1,2}$/;
const rawRegex = /^(\[(?:\d{2}:){1,2}\d{2}\] |)(.*)$/;
return quote.split('\n').map((line, test) => {
// eslint-disable-next-line max-len
if (test = line.match(chatRegex)) return smogon ? `[SIZE=1][COLOR=rgb(102, 102, 102)]${test[1]}[/COLOR][/SIZE][SIZE=2][COLOR=rgb(102, 102, 102)] ${test[2]}[/COLOR][COLOR=rgb(${tools.HSLtoRGB(...tools.HSL(test[3]).hsl).join(', ')})][B]${test[3]}[/B]:[/COLOR] ${test[4]}[/SIZE]` : `<div class="chat chatmessage-a" style="padding:3px 0;"><small>${test[1] + test[2]}</small><span class="username">${utg ? `<username>${test[3]}:</username>` : tools.colourize(`${test[3]}:`)}</span><em> ${test[4]}</em></div>`;
// eslint-disable-next-line max-len
else if (test = line.match(meRegex)) return `<div class="chat chatmessage-${toID(test[3])}" style="padding:3px 0;"><small>${test[1]}</small>${tools.colourize('• ', test[3])}<em><small>${test[2]}</small><span class="username">${test[3].slice(1, -1)}</span><i> ${test[4]}</i></em></div>`;
// eslint-disable-next-line max-len
else if (test = line.match(jnlRegex)) return `<div class="message" style="padding:3px 0;"><small style="color: #555555"> ${test[0]}<br /></small></div>`;
// eslint-disable-next-line max-len
else if (test = line.match(rawRegex)) return `<div class="chat chatmessage-partbot" style="padding:3px 0;"><small>${test[1]}</small>${test[2]}</div>`;
}).join(smogon ? '\n' : '');
};
exports.aliasDB = require('./ALIASES/commands.json');
exports.pmAliasDB = require('./ALIASES/pmcommands.json');
exports.goAliasDB = require('./ALIASES/go.json');
exports.commandAlias = function (alias) {
if (exports.aliasDB[toID(alias)]) alias = exports.aliasDB[toID(alias)];
return toID(alias);
};
exports.pmCommandAlias = function (alias) {
if (exports.pmAliasDB[toID(alias)]) alias = exports.pmAliasDB[toID(alias)];
return toID(alias);
};
exports.rankLevel = function (name, room) {
const userid = toID(name);
switch ((() => {
let override;
const roomName = Bot.rooms[room]?.users.find(u => toID(u) === userid);
if (Bot.auth.admin.includes(userid)) return 'admin';
else if (Bot.auth.coder.includes(userid)) return 'coder';
else if (Bot.auth.locked.includes(userid)) return 'locked';
else if (Bot.rooms[room]?.auth && (override = Object.entries(Bot.rooms[room].auth).find(([rank, list]) => {
return list.includes(userid);
})?.[0])) return override;
else if (Bot.auth.alpha.includes(userid) || room !== 'global' && Bot.rooms[room] && /^[~&#@\*]/.test(roomName)) {
return 'alpha';
} else if (Bot.auth.beta.includes(userid) || room !== 'global' && Bot.rooms[room] && /^[%§]/.test(roomName)) {
return 'beta';
} else if (Bot.auth.gamma.includes(userid) || room !== 'global' && Bot.rooms[room] && /^[+]/.test(roomName)) {
return 'gamma';
} else if (room !== 'global' && Bot.rooms[room] && /^[!]/.test(roomName)) {
return 'muted';
} else return 'reg';
})()) {
case 'admin': return 10;
case 'coder': return 9;
case 'alpha': return 6;
case 'beta': return 5;
case 'gamma': return 4;
case 'reg': return 3;
case 'muted': return 2;
case 'locked': return 1;
}
};
exports.hasPermission = function (user, rank, room) {
let auth;
if (typeof user === 'number') auth = user;
else auth = tools.rankLevel(user, room);
let req;
switch (rank) {
case 'admin':
req = 9;
break;
case 'coder':
req = 8;
break;
case 'alpha':
req = 5;
break;
case 'beta':
req = 4;
break;
case 'gamma':
req = 3;
break;
case 'none':
req = 2;
break;
case 'muted':
req = 1;
break;
case 'locked':
req = 0;
break;
default:
req = 0;
}
if (auth > req) return true;
else return false;
};
exports.getRoom = function (room) {
room = (room?.id || room?.name || room || '').toString().toLowerCase().replace(/[^a-z0-9-]/g, '');
if (Bot.rooms.hasOwnProperty(room)) return room;
return fs.readdirSync('./data/ROOMS').find(roomFile => {
try {
const required = require(`./ROOMS/${roomFile}`);
if (required.aliases.includes(room)) return true;
} catch {}
})?.slice(0, -5) || room;
};
exports.blockedCommand = function (command, room) {
try {
room = room.toLowerCase().replace(/[^a-z0-9-]/g, '');
command = tools.commandAlias(command);
return Boolean(require(`./ROOMS/${room}.json`).disabled.includes(command));
} catch {
return false;
}
};
exports.canHTML = function (room) {
if (!room) return false;
if (!Bot.rooms[room]) return false;
if (['*', '#', '&', '#', '★'].includes(Bot.rooms[room].rank)) return true;
return false;
};
exports.listify = function (array, delim = ', ', concat = ' and ') {
if (!Array.isArray(array)) throw new TypeError(`Expected array as Array`);
if (array.length < 3) return array.join(concat);
const body = array.slice(0, -1).map(term => term + delim).join('').slice(0, concat.startsWith(' ') ? -1 : this.length);
const suffix = (concat.startsWith(' ') ? '' : ' ') + concat + array.at(-1);
return body + suffix;
};
exports.uploadToPastie = function (text) {
return axios.post('https://pastie.io/documents', text).then(res => `https://pastie.io/raw/${res.data}`);
};
exports.warmup = function (room, commandName) {
if (!cooldownObject[room] || !cooldownObject[room][commandName]) return;
cooldownObject[room][commandName] = false;
return;
};
exports.setCooldown = function (commandName, room, commandRequire) {
if (!commandRequire || !commandName) return;
if (!(typeof commandName === 'string') || !(typeof commandRequire === 'object') || Array.isArray(commandRequire)) return;
if (!commandRequire.cooldown) return;
if (!cooldownObject[room]) cooldownObject[room] = {};
cooldownObject[room][commandName] = true;
return setTimeout(tools.warmup, commandRequire.cooldown, room, commandName);
};
exports.HSL = function (name, original) {
name = toID(name);
const out = { source: name, hsl: null };
if (COLORS[name] && name !== 'constructor' && !original) {
out.base = exports.HSL(name, true);
name = COLORS[name];
out.source = name;
}
const hash = require('crypto').createHash('md5').update(name, 'utf8').digest('hex');
const H = parseInt(hash.substr(4, 4), 16) % 360;
const S = parseInt(hash.substr(0, 4), 16) % 50 + 40;
let L = Math.floor(parseInt(hash.substr(8, 4), 16) % 20 + 30);
const C = (100 - Math.abs(2 * L - 100)) * S / 100 / 100;
const X = C * (1 - Math.abs(H / 60 % 2 - 1));
const m = L / 100 - C / 2;
let R1;
let G1;
let B1;
switch (Math.floor(H / 60)) {
case 1:
R1 = X;
G1 = C;
B1 = 0;
break;
case 2:
R1 = 0;
G1 = C;
B1 = X;
break;
case 3:
R1 = 0;
G1 = X;
B1 = C;
break;
case 4:
R1 = X;
G1 = 0;
B1 = C;
break;
case 5:
R1 = C;
G1 = 0;
B1 = X;
break;
case 0:
default:
R1 = C;
G1 = X;
B1 = 0;
break;
}
const R = R1 + m;
const G = G1 + m;
const B = B1 + m;
const lum = R * R * R * 0.2126 + G * G * G * 0.7152 + B * B * B * 0.0722;
let HLmod = (lum - 0.2) * -150;
if (HLmod > 18) HLmod = (HLmod - 18) * 2.5;
else if (HLmod < 0) HLmod = (HLmod - 0) / 3;
else HLmod = 0;
const Hdist = Math.min(Math.abs(180 - H), Math.abs(240 - H));
if (Hdist < 15) HLmod += (15 - Hdist) / 3;
L += HLmod;
out.hsl = [
H,
S,
L
];
return out;
};
exports.colourize = function (text, name, useOriginal) {
if (!name) name = toID(text);
if (COLORS[toID(name)] && !useOriginal) name = COLORS[toID(name)];
const [H, S, L] = exports.HSL(name).hsl;
return '<strong style=\"' + `color:hsl(${H},${S}%,${L}%);` + '\">' + tools.escapeHTML(text) + '</strong>';
};
exports.escapeHTML = function (str) {
if (!str) return '';
return ('' + str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\//g, '/');
};
exports.unescapeHTML = function (str) {
if (!str) return '';
return ('' + str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(///g, '/');
};
exports.HSLtoRGB = function (h, s, l) {
// input [[0, 360], [0, 100], [0, 100]]
let r, g, b;
h /= 360;
s /= 100;
l /= 100;
if (s === 0) r = g = b = l;
else {
const hue2rgb = (p, q, t) => {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
};
exports.RGBtoHEX = function (r, g, b) {
const hex = '#' + ('0' + r.toString(16)).slice(-2) + ('0' + g.toString(16)).slice(-2) + ('0' + b.toString(16)).slice(-2);
return hex.toUpperCase();
};
exports.HSLtoHEX = function (h, s, l) {
return exports.RGBtoHEX(...exports.HSLtoRGB(h, s, l));
};
exports.modeArray = function (arr) {
if (!Array.isArray(arr)) return;
const arrObj = {};
arr.forEach(elem => {
if (!arrObj['elem' + elem]) arrObj['elem' + elem] = 1;
else arrObj['elem' + elem]++;
});
const maxF = Object.values(arrObj).sort((a, b) => b - a)[0];
return Object.keys(arrObj).filter(elem => arrObj[elem] === maxF).map(elem => elem.substr(4)).sort();
};
exports.toHumanTime = function (millis) {
if (typeof millis === 'string') millis = parseInt(millis);
if (typeof millis !== 'number') return;
const time = {};
time.year = Math.floor(millis / (365 * 24 * 60 * 60 * 1000));
millis %= 365 * 24 * 60 * 60 * 1000;
time.week = Math.floor(millis / (7 * 24 * 60 * 60 * 1000));
millis %= 7 * 24 * 60 * 60 * 1000;
time.day = Math.floor(millis / (24 * 60 * 60 * 1000));
millis %= 24 * 60 * 60 * 1000;
time.hour = Math.floor(millis / (60 * 60 * 1000));
millis %= 60 * 60 * 1000;
time.minute = Math.floor(millis / (60 * 1000));
millis %= 60 * 1000;
time.second = Math.floor(millis / 1000);
millis %= 1000;
time.millisecond = millis;
const output = [];
let foundFirst = false;
let foundSecond = false;
Object.keys(time).forEach(val => {
if (foundFirst && !foundSecond) {
if (time[val] === 0);
else output.push(time[val] + ' ' + val + (time[val] === 1 ? '' : 's'));
foundSecond = true;
} else {
if (time[val] && !foundSecond) {
foundFirst = true;
output.push(time[val] + ' ' + val + (time[val] === 1 ? '' : 's'));
}
}
});
return output.join(' and ') || '0 seconds';
};
exports.fromHumanTime = function (text) {
text = text.replace(/(?:^| )an? /ig, '1');
text = text.toLowerCase().replace(/[^a-z0-9\.:]/g, '');
const digital = text.match(/^(?:(\d+):)?(\d+):(\d+):(\d+)$/);
if (digital) {
const [match, day, hrs, min, sec] = digital;
return day * 24 * 60 * 60 * 1000 + hrs * 60 * 60 * 1000 + min * 60 * 1000 + sec * 1000;
} else text = text.replace(/:/g, '');
let time = 0;
const units = {
mis: {
regex: /\d+(?:\.\d+)?m(?:illi)?s(?:ec(?:ond?)?s?)?/,
length: 1
},
sec: {
regex: /\d+(?:\.\d+)?(?:s(?:ec(?:onds?)?)?)/,
length: 1000
},
min: {
regex: /\d+(?:\.\d+)?m(?:in(?:ute?)?s?)?/,
length: 60 * 1000
},
hrs: {
regex: /\d+(?:\.\d+)?(?:h(?:(?:ou)?r)?)s?/,
length: 60 * 60 * 1000
},
day: {
regex: /\d+(?:\.\d+)?d(?:ays?)?/,
length: 24 * 60 * 60 * 1000
},
wks: {
regex: /\d+(?:\.\d+)?(?:w(?:(?:ee)?k)?)s?/,
length: 7 * 24 * 60 * 60 * 1000
}
};
Object.values(units).forEach(unit => {
const match = text.match(unit.regex);
if (!match) return;
text = text.replace(match[0], '');
time += parseFloat(match[0]) * unit.length;
});
return time;
};
exports.getSetsFrom = function (link) {
switch (link.split('.')[0]) {
case 'pokepast': {
// TODO: Use axios
if (!link.endsWith('/json')) link += '/json';
require('request')(link, (error, response, body) => {
if (error) throw error;
const data = JSON.parse(body).paste;
return data.replace(/\r\n/g, '');
});
}
}
};
exports.utm = function (text) {
return text.split(/\n\s*\n/)
.map(mon => parseMon(mon))
.filter(mon => typeof mon === 'object')
.map(mon => {
// eslint-disable-next-line max-len
return `${mon.name}|${mon.species || ''}|${toID(mon.item)}|${toID(mon.ability)}|${mon.moves.map(move => toID(move)).join(',')}|${mon.nature}|${Object.values(mon.evs).filter(ev => ev === 0).length === 6 ? '' : Object.values(mon.evs).map(ev => ev || '').join(',')}|${mon.gender || ''}|${Object.values(mon.ivs).filter(iv => iv === 31).length === 6 ? '' : Object.values(mon.ivs).map(iv => iv === 31 ? '' : iv).join(',')}|${mon.shiny ? 'S' : ''}|${mon.level === 100 ? '' : mon.level}|${mon.happiness !== 255 || mon.hiddenpower ? [mon.happiness || '', mon.hiddenpower || '', ''].join(',') : ''}`;
}).join(']');
};
exports.runEarly = function (timer) {
if (!timer) return false;
timer._onTimeout();
clearTimeout(timer);
return true;
};
exports.getPorts = function (name, source) {
if (!Array.isArray(source)) return null;
const front = source.filter(elem => {
if (!elem) return false;
elem = toID(elem);
if (name.startsWith(elem)) return true;
for (let i = 2; i < elem.length; i++) {
if (name.startsWith(elem.slice(elem.length - i, elem.length))) return true;
}
return false;
});
const end = source.filter(elem => {
if (!elem) return false;
elem = toID(elem);
if (elem.startsWith(name)) return true;
for (let i = 2; i < name.length; i++) {
if (elem.startsWith(name.slice(name.length - i, name.length))) return true;
}
return false;
});
return [front.sort(), end.sort()];
};
exports.board = require('./TABLE/boards.js').render;
exports.toName = function (text) {
text = text.trim();
return text[0].toUpperCase() + text.substr(1);
};
exports.getEffectiveness = function (mon1, mon2) {
if (Array.isArray(mon1)) mon1 = mon1.map(t => tools.toName(toID(t)));
if (Array.isArray(mon2)) mon2 = mon2.map(t => tools.toName(toID(t)));
if (typeof mon1 === 'string') {
if (data.pokedex[toID(mon1)]) mon1 = data.pokedex[toID(mon1)].types;
else if (typelist.includes(mon1.toLowerCase())) mon1 = [tools.toName(mon1)];
}
if (typeof mon2 === 'string') {
if (data.pokedex[toID(mon2)]) mon2 = data.pokedex[toID(mon2)].types;
else if (typelist.includes(mon2.toLowerCase())) mon2 = [tools.toName(mon2)];
}
if (!Array.isArray(mon1) || !Array.isArray(mon2)) return null;
let x = 1;
mon1.forEach(offType => {
if (!data.typechart[offType]) return;
mon2.forEach(defType => {
if (!data.typechart[defType]) return;
switch (data.typechart[defType].damageTaken[offType]) {
case 0: x *= 1; break;
case 1: x *= 2; break;
case 2: x *= 0.5; break;
case 3: x *= 0; break;
}
});
});
return x;
};
exports.toSprite = function (mon, full, style) {
const cds = require('./DATA/iconcoords.json');
if (typelist.includes(toID(mon))) {
mon = toID(mon);
mon = mon[0].toUpperCase() + mon.substr(1);
// eslint-disable-next-line max-len
return `<img src="https://play.pokemonshowdown.com/sprites/types/${mon}.png" alt="${mon}" class="pixelated" width="32" height="14" style="${style}">`;
}
if (!cds[toID(mon)]) return mon;
mon = toID(mon);
// eslint-disable-next-line max-len
if (!full) return `<span class="picon" style="background: transparent url('https://play.pokemonshowdown.com/sprites/pokemonicons-sheet.png?v2') no-repeat scroll ${cds[mon][0]}px ${cds[mon][1]}px; ${style}"></span>`;
// eslint-disable-next-line max-len
return `<span class="picon" style="background: transparent url('https://play.pokemonshowdown.com/sprites/pokemonicons-sheet.png?v2') no-repeat scroll ${cds[mon][0]}px ${cds[mon][1]}px; display: inline-block; width: 40px; height: 30px; ${style}"></span>`;
};
exports.random = function (input) {
switch (typeof input) {
case 'number': return Math.floor(Math.random() * input);
case 'object': {
if (Array.isArray(input)) {
input = input.slice().sort((a, b) => a - b);
if (input.length === 2) return input[0] + Math.floor(Math.random() * (input[1] - input[0]));
return null;
}
const keys = Object.keys(input), values = Object.values(input);
let sum = 0;
values.forEach(num => {
if (Array.isArray(num)) num = num.reduce((a, b) => a * b, 1);
if (!(num >= 0)) throw new TypeError(`Object values must be non-negative numbers`);
sum += num;
});
if (!sum) throw new Error(`The sum of object values must be positive!`);
let seed = Math.random() * sum;
for (const val in input) {
seed -= Array.isArray(input[val]) ? input[val].reduce((a, b) => a * b, 1) : input[val];
if (seed < 0) return val;
}
return null;
}
default: return null;
}
};
exports.deepClone = function (aObject) {
if (!aObject) return aObject;
const bObject = Array.isArray(aObject) ? [] : {};
for (const k in aObject) {
const v = aObject[k];
bObject[k] = typeof v === 'object' ? exports.deepClone(v) : v;
}
return bObject;
};
exports.getAlts = async function alts (user, trace = 1) {
trace = 1;
if (typeof user === 'object') user = user.name || user.username || user.userid || user.id;
if (typeof user !== 'string') throw new TypeError('Username must be a string.');
user = toID(user);
if (!trace) return await DATABASE.getAlts(user) || [];
const done = new Set([user]);
let next = await DATABASE.getAlts(user) || [];
let i = 0;
while (next.length) {
const newNext = [];
if (i++ > trace) break;
if (next.map(alt => {
if (done.has(alt)) return true;
const alts = await(DATABASE.getAlts(alt)) || [];
done.add(alt);
if (!alts.length) return true;
else newNext.push(...alts);
}).every(skip => skip)) break;
next = newNext;
}
return [...done];
};
/************************
* Shops *
************************/
// TODO: Better points system; migrate point metadata to room
exports.loadShops = function (...shops) {
if (!shops.length) shops = fs.readdirSync('./data/SHOPS').map(shop => shop.slice(0, shop.length - 5));
shops.map(shop => shop.toLowerCase().replace(/[^a-z0-9-]/g, ''));
shops.forEach(shop => {
if (!Bot.rooms[shop]) return console.log(`Not in ${shop} to load Shop.`);
fs.readFile(`./data/SHOPS/${shop}.json`, 'utf8', (err, file) => {
if (err) return;
const dat = JSON.parse(file);
Bot.rooms[shop].shop = dat;
console.log(`Loaded the ${Bot.rooms[shop].title} Shop.`);
});
});
};
exports.updateShops = function (...shops) {
if (!shops.length) shops = fs.readdirSync('./data/SHOPS').map(shop => shop.slice(0, shop.length - 5));
shops.map(shop => shop.toLowerCase().replace(/[^a-z0-9-]/g, ''));
shops.forEach(shop => {
if (!Bot.rooms[shop]) return console.log(`Not in ${shop} to update Shop.`);
fs.writeFile(`./data/SHOPS/${shop}.json`, JSON.stringify(Bot.rooms[shop].shop, null, 2), (err) => {
if (err) return;
});
});
};
exports.loadLB = function (...rooms) {
if (!rooms.length) rooms = fs.readdirSync('./data/POINTS').map(room => room.slice(0, room.length - 5));
rooms.map(room => room.toLowerCase().replace(/[^a-z0-9-]/g, ''));
rooms.forEach(room => {
if (!Bot.rooms[room]) return console.log(`Not in ${room} to load the leaderboard.`);
fs.readFile(`./data/POINTS/${room}.json`, 'utf8', (err, file) => {
if (err) return;
const dat = JSON.parse(file);
Bot.rooms[room].lb = dat;
console.log(`Loaded the ${Bot.rooms[room].title} leaderboard.`);
});
});
};
exports.updateLB = function (...rooms) {
if (!rooms.length) rooms = fs.readdirSync('./data/POINTS').map(room => room.slice(0, room.length - 5));
rooms.map(room => room.toLowerCase().replace(/[^a-z0-9-]/g, ''));
rooms.forEach(room => {
if (!Bot.rooms[room]) return console.log(`Not in ${room} to update leaderboard.`);
fs.writeFile(`./data/POINTS/${room}.json`, JSON.stringify(Bot.rooms[room].lb, null, 2), (err) => {
if (err) return;
});
});
};
exports.addPoints = function (type, username, points, room) {
return new Promise((resolve, reject) => {
if (typeof type !== 'number') return reject(new Error('Type must be a number.'));
points = parseInt(points);
if (isNaN(points)) return reject(new Error('Points must be a valid number'));
const user = toID(username);
if (!room || !Bot.rooms[room].lb) return reject(new Error('Invalid room / no leaderboard'));
if (type >= Bot.rooms[room].lb.points.length) return reject(new Error('Type is too high!'));
if (!Bot.rooms[room].lb.users[user]) {
Bot.rooms[room].lb.users[user] = {
name: username,
points: Array.from({ length: Bot.rooms[room].lb.points.length }).map(t => 0)
};
}
Bot.rooms[room].lb.users[user].points[type] += points;
tools.updateLB(room);
return resolve(username);
});
};
/************************
* Games *
************************/
// TODO: This should be contained in the command
exports.newDeck = function (type, amt) {
// TODO: Move all of these to the individual game command files
if (!type) type = 'regular';
type = toID(type);
switch (type) {
case 'regular': case 'reg': {
if (!amt) amt = 1;
const deck = [];
const suits = ['H', 'S', 'D', 'C'];
const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
for (let i = 0; i < amt; i++) suits.forEach(suit => ranks.forEach(rank => deck.push(rank + suit)));
return deck;
}
case 'explodingvoltorb': case 'ev': {
if (!amt || amt < 2 || amt > 5) return null;
const deck = [], post = [];
const amounts = {
snorlax: 5,
meowth: 4,
liepard: 4,
skitty: 4,
lugia: 4,
espurr: 3,
flareon: 7,
jolteon: 7,
vaporeon: 7,
espeon: 7,
umbreon: 7
};
Object.entries(amounts).forEach(([mon, amount]) => deck.push(...Array(amount).fill(mon)));
post.push(...Array(amt).fill('voltorb'));
post.push(...Array(6).fill('quagsire'));
// for (let i = 0; i < 5; i++) deck.push('snorlax');
// for (let i = 0; i < 4; i++) deck.push('meowth');
// for (let i = 0; i < 4; i++) deck.push('liepard');
// for (let i = 0; i < 4; i++) deck.push('skitty');
// for (let i = 0; i < 4; i++) deck.push('lugia');
// for (let i = 0; i < 3; i++) deck.push('espurr');
// for (let i = 0; i < 7; i++) deck.push('flareon');
// for (let i = 0; i < 7; i++) deck.push('jolteon');
// for (let i = 0; i < 7; i++) deck.push('vaporeon');
// for (let i = 0; i < 7; i++) deck.push('espeon');
// for (let i = 0; i < 7; i++) deck.push('umbreon');
// for (let i = 1; i < amt; i++) post.push('voltorb');
// for (let i = 0; i < 6; i++) post.push('quagsire');
return [deck, post];
}
}
};
exports.toShuffleImage = function (mon) {
mon = mon.toLowerCase();
switch (mon) {
case 'espeon': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/e/ef/Espeon.png';
case 'espurr': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/9/99/Espurr.png';
case 'flareon': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/1/17/Flareon.png';
case 'jolteon': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/1/1e/Jolteon.png';
case 'liepard': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/3/3b/Liepard.png';
case 'lugia': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/a/a7/Lugia.png';
case 'meowth': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/9/99/Meowth.png';
case 'quagsire': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/1/1b/Quagsire.png';
case 'skitty': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/f/f0/Skitty.png';
case 'snorlax': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/0/0b/Snorlax.png';
case 'umbreon': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/9/9f/Umbreon.png';
case 'vaporeon': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/f/fc/Vaporeon.png';
case 'voltorb': return 'https://vignette.wikia.nocookie.net/pkmnshuffle/images/8/80/Voltorb.png';
default: return '';
}
};
exports.deal = function (players) {
const out = { players: {} }, cards = exports.newDeck('ev', players.length);
if (!cards) return null;
const [deck, post] = cards;
deck.shuffle();
players.forEach(player => out.players[toID(player)] = [post.pop(), deck.splice(0, 7)]);
out.deck = deck.concat(post).shuffle();
return out;
};
exports.cardFrom = function (str) {
if (data.pokedex[str]) return data.pokedex[str].name;
if (!str || !/^(?:[AJQK2-9]|10)[HSDC]$/.test(str)) return null;
const arr = str.split(''), suit = { H: '♡', S: '♠', D: '♢', C: '♣' }[arr.pop()];
return [arr.join(''), suit];
};
exports.cardWeight = function (card) {
if (!Array.isArray(card)) card = tools.cardFrom(card);
if (!card) return null;
if (/\d/.test(card[0])) return parseInt(card);
if (['J', 'Q', 'K'].includes(card[0])) return 10;
if (card[0] === 'A') return 1;
return null;
};
exports.sumBJ = function (cards) {
if (!Array.isArray(cards)) return null;
if (typeof cards[0] === 'string') cards = cards.map(card => tools.cardFrom(card));
let sum = 0, aces = 0;
cards.forEach(card => {
let wt = tools.cardWeight(card);
if (!wt) return;
if (wt === 1) {
wt = 11;
aces++;
}
return sum += wt;
});
while (sum > 21 && aces > 0) {
sum -= 10;
aces--;
}
return sum;
};
exports.getActions = function (hand) {
if (!hand || !Array.isArray(hand)) return null;
const actions = [];
let allFive = true;
if (hand.includes('skitty')) actions.push('Skitty');
if (hand.includes('meowth')) actions.push('Meowth');
if (hand.includes('liepard')) actions.push('Liepard');
if (hand.includes('lugia')) actions.push('Lugia');
if (hand.includes('espurr')) actions.push('Espurr');
['espeon', 'flareon', 'jolteon', 'umbreon', 'vaporeon'].forEach(vee => {
const dupe = hand.filter(m => m === vee).length;
if (dupe >= 2) actions.push(`2x${data.pokedex[vee].name}`);
if (dupe >= 3) actions.push(`3x${data.pokedex[vee].name}`);
if (!hand.includes(vee)) allFive = false;
});
if (allFive) actions.push('Eevee Power');
return actions;
};
exports.handHTML = function (hand) {
if (!hand || !Array.isArray(hand)) return null;
// eslint-disable-next-line max-len
return '<center> ' + hand.filter(card => ['espeon', 'espurr', 'flareon', 'jolteon', 'liepard', 'lugia', 'meowth', 'quagsire', 'skitty', 'snorlax', 'umbreon', 'vaporeon', 'voltorb'].includes(card)).map(card => `<img src="${exports.toShuffleImage(card)}" height="48" width="48">`).join('') + '</center>';
};
exports.scrabblify = function (text) {
if (!typeof text === 'string') return 0;
const tarr = text.toUpperCase().split('');
function points (letter) {
if (!typeof letter === 'string' || !letter.length === 1) return 0;
if ('EAOTINRSLU'.includes(letter)) return 1;
else if ('DG'.includes(letter)) return 2;
else if ('CMBP'.includes(letter)) return 3;
else if ('HFWYV'.includes(letter)) return 4;
else if ('K'.includes(letter)) return 5;
else if ('JX'.includes(letter)) return 8;
else if ('ZQ'.includes(letter)) return 10;
else if ('1234567890'.includes(letter)) return ~~letter;
else return 0;
}
return tarr.reduce((x, y) => x + points(y), 0);
};
exports.queryGO = function (name) {
if (typeof name !== 'string') throw new TypeError('Expected type \'string\' in aliasGO');
name = toID(name);
const formeNames = {
alola: ['a', 'alola', 'alolan'],
galar: ['g', 'galar', 'galarian'],
mega: ['m', 'mega'],
primal: ['p', 'primal']
};
const alts = [name];
Object.entries(formeNames).forEach(([key, values]) => {
values.forEach(val => {
if (name.startsWith(val)) alts.push(name.substr(val.length) + key);
if (name.endsWith(val)) alts.push(name.slice(0, -val.length) + key);
});
});
return alts.map(alt => alt === 'constructor' ? 'null' : toID(exports.goAliasDB[alt] || alt)).map(alt => {
if (data.go.pokedex[alt]) return {
type: 'pokemon',
info: data.go.pokedex[alt]
};
else if (data.go.moves.fast[alt]) return {
type: 'fast_move',
info: data.go.moves.fast[alt]
};
else if (data.go.moves.charged[alt]) return {
type: 'charged_move',
info: data.go.moves.charged[alt]
};
}).find(res => res);
};
exports.getCP = function (mon, level, ivs) {
if (!level) level = 40;
if (!ivs) ivs = { atk: 15, def: 15, sta: 15 };
if (Array.isArray(ivs)) ivs = { atk: ivs[0], def: ivs[1], sta: ivs[2] };
const CP_M = require('./DATA/pokemongocp.json');
mon = toID(mon);
if (mon === 'constructor') return 0;
mon = data.go.pokedex[mon];
if (!mon) return 0;
const stats = mon.baseStats;
const atk = stats.atk + ivs.atk, def = stats.def + ivs.def, sta = stats.sta + ivs.sta;
const out = Math.floor(atk * def ** 0.5 * sta ** 0.5 * (CP_M[level] || 0.7903) ** 2 / 10);
return out > 10 ? out : 10;
};
/************************
* Prototypes *
************************/
String.prototype.frequencyOf = function (text) {
if (!typeof text === 'string') return;
return this.split(text).length - 1;
};
String.prototype.splitFirst = function (delim, amount) {
if (typeof amount !== 'number') amount = 1;
if (amount < 0 || amount - parseInt(amount)) throw new Error('\'amount\' must be a non-negative integer');
if (typeof delim !== 'string' && !delim instanceof RegExp) throw new TypeError(`'delim' must be a string / regular expression`);
const out = [];
let input = this.toString();
let isR = false;
if (delim instanceof RegExp) {
isR = true;
delim = new RegExp(delim, delim.flags.replace('g', ''));
}
for (let i = 0; i < amount; i++) {
if (isR) {
const match = input.match(delim);
if (!match) return [...out, input];
const m = match[0];
out.push(input.substr(0, match.index));
input = input.substr(match.index + m.length);
for (let j = 1; j < match.length; j++) out.push(match[j]);
} else {
const match = input.indexOf(delim);
if (match < 0) return [...out, input];
out.push(input.substr(0, match));
input = input.substr(match + delim.length);
}
}
out.push(input);
return out;
};
Array.prototype.shuffle = function () {
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
return Array.from(this);
};
Array.prototype.remove = function (...terms) {
let out = true;
terms.forEach(term => {
if (this.indexOf(term) >= 0) this.splice(this.indexOf(term), 1);
else out = false;
});
return out;
};
Array.prototype.random = function (amount) {
if (!amount || typeof amount !== 'number') return this[Math.floor(Math.random() * this.length)];
const sample = Array.from(this), out = [];
let i = 0;
while (sample.length && i++ < amount) {
const term = sample[Math.floor(Math.random() * sample.length)];
out.push(term);
sample.remove(term);
}
return out;
};
Set.prototype.find = function (fn) {
for (const term of this) if (fn(term)) return term;
return undefined;
};
// TODO: Rehaul this entire file holy shit
// TODO: Add a cmd function
<file_sep>/discord/utm.js
module.exports = {
help: `HELP`,
pm: true,
commandFunction: function (args, message, Bot) {
if (!args.length) return message.channel.send(unxa);
function parseMon (mon) {
if (!mon.replace(/[^a-zA-Z0-9]/g, '')) return true;
const out = {
name: null,
species: null,
gender: null,
level: 100,
item: null,
ability: null,
shiny: false,
happiness: 255,
hiddenpower: null,
evs: {
hp: 0,
atk: 0,
def: 0,
spa: 0,
spd: 0,
spe: 0
},
ivs: {
hp: 31,
atk: 31,
def: 31,
spa: 31,
spd: 31,
spe: 31
},
nature: 'Serious',
moves: []
};
const lines = mon.split('\n').map(line => line.trim());
let line = lines.shift().split(' @ ');
if (line[1]) out.item = line[1];
out.gender = line[0].match(/\([MF]\)$/);
if (out.gender) {
out.gender = out.gender[0][1];
line[0] = line[0].slice(0, -4);
}
out.species = line[0].match(/\(.*\)/);
if (out.species) out.species = toID(out.species[0].slice(1, -1));
line[0] = line[0].replace(/\(.*\)/, '');
out.name = line[0].trim();
line = lines.shift().split('Ability: ');
if (line.length !== 2) return null;
out.ability = line[1].trim();
line = lines.shift();
if (line.startsWith('Level: ')) {
out.level = parseInt(line.substr('Level: '.length).trim());
if (isNaN(out.level)) return null;
line = lines.shift();
}
if (line.startsWith('Shiny: ')) {
out.shiny = true;
line = lines.shift();
}
if (line.startsWith('Happiness: ')) {
out.happiness = parseInt(line.substr('Happiness: '.length).trim());
line = lines.shift();
}
if (line.startsWith('Hidden Power: ')) {
out.happiness = line.substr('Hidden Power: '.length).trim();
line = lines.shift();
}
if (line.startsWith('EVs: ')) {
line.substr(5).split(' / ').forEach(stat => {
stat = stat.split(' ');
const val = parseInt(stat[0]);
if (isNaN(val)) return null;
out.evs[stat[1].toLowerCase()] = val;
});
line = lines.shift();
}
if (line.endsWith(' Nature')) {
out.nature = line.split(' ')[0];
line = lines.shift();
}
if (line.startsWith('IVs: ')) {
line.substr(5).split(' / ').forEach(stat => {
stat = stat.split(' ');
const val = parseInt(stat[0]);
if (isNaN(val)) return null;
out.ivs[stat[1].toLowerCase()] = val;
});
line = lines.shift();
}
while (line && line.startsWith('- ')) {
out.moves.push(line.substr(2));
line = lines.shift();
}
return out;
}
let link = args.join(' ');
if (!link.endsWith('/raw')) link += '/raw';
if (!/^https?:\/\/pokepast\.es\/[a-z0-9]+\/raw$/.test(link)) {
return message.channel.send('Invalid link - I can only use Pokepast.es. :(');
}
require('request')(link, (error, response, body) => {
if (error) return message.channel.send('Unable to get the data...');
try {
message.channel.send("```" + tools.utm(body) + "```");
} catch (e) {
message.channel.send(`Something went wrong: ${e.message}`);
}
});
}
};
<file_sep>/commands/global/levenshtein.js
module.exports = {
cooldown: 1,
help: `Calculates the Levenshtein difference between two strings, separated by commas.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
const lv = require('js-levenshtein');
const input = args.join(' ').split(',').map(term => term.trim().toLowerCase());
if (input.length !== 2) return Bot.pm(by, 'Expected two strings.');
const output = lv(...input);
if (tools.hasPermission(by, 'gamma', room)) {
Bot.say(room, `The Levenshtein difference between the two given strings is ${output}.`);
} else Bot.pm(by, `The Levenshtein difference between the two given strings is ${output}.`);
}
};
<file_sep>/discord/analyze.js
module.exports = {
help: `Analyzes a paste. Syntax: ${prefix}analyze (paste link), (optional: type of Challenge)`,
guildOnly: '515170462037311498',
commandFunction: function (args, message, Bot) {
if (!message.member.roles.cache.find(role => role.name === 'Validator')) {
return message.channel.send('Access denied.').then(msg => msg.delete({ timeout: 3000 }));
}
args = args.join(' ').split(/\s*,\s*/);
if (!args.length) return message.channel.send(unxa).then(msg => msg.delete({ timeout: 3000 }));
const paste = args[0];
if (!/^https?:\/\/pokepast\.es\/[a-z0-9]+(?:\/raw)?$/.test(paste)) return message.channel.send("Inavlid paste.");
if (!args[0].endsWith('/raw')) args[0] += '/raw';
axios.get(paste).then(res => {
let replays = res.data.match(/https?:\/\/replay.pokemonshowdown.com\/gen[78]1v1-\d{9,10}(?:-[a-z0-9]+)?/g);
if (!replays) return Bot.log("Couldn't find replays.");
replays = replays.map(replay => replay + '.log');
Promise.all(replays.map(replay => {
return new Promise((resolve, reject) => {
axios.get(replay).then(response => {
const players = response.data.match(/\n\|player\|p[12]\|[^|]+/g);
if (!players) return message.channel.send("RED ALERT RED ALERT");
resolve(players.map(t => toID(t.split('|')[3])));
}).catch(reject);
});
})).then(allPlayers => {
let id;
if (!allPlayers.filter(s => !s.includes(allPlayers[0][0])).length) id = allPlayers[0][0];
else if (!allPlayers.filter(s => !s.includes(allPlayers[0][1])).length) id = allPlayers[0][1];
else return message.channel.send("Errm, there wasn't a user that was in all of those.");
const output = { userid: id, team: {} };
Promise.all(replays.map(replay => {
return new Promise((resolve, reject) => {
try {
axios.get(replay).then(res => {
const data = res.data;
const result = {
id: parseInt(replay.split(/gen[78]1v1-/)[1].split('-')[0]),
type: false,
rating: [],
LL: false
};
const input = data.split('\n');
let inThis = null, enemy = false;
for (const line of input) {
const args = line.split('|');
switch (args[1]) {
case 'player': {
if (!args[3]) break;
else if (toID(args[3]) === id) {
inThis = args[2];
output.avatar = args[4];
output.username = args[3];
} else if (enemy) {
if (inThis) break;
Bot.log(args[3]);
reject(new Error("Player not found."));
return;
} else enemy = true;
break;
}
case 'teamsize': {
if (!inThis) {
reject(new Error("Expected teamsize after player."));
return;
}
if (args[2] !== inThis) result.oppSize = parseInt(args[3]);
break;
}
case 'poke': {
if (!inThis) {
reject(new Error("Expected poke after player."));
return;
}
if (args[2] === inThis) {
const species = args[3].split(', ')[0].split('-')[0];
if (!output.team[species]) output.team[species] = {
species: undefined,
level: 100,
moves: []
};
if (/^L\d{1,2}$/.test(args[3].split(', ')[1])) {
output.team[species].level = parseInt(args[3].split(', ')[1].substr(1));
}
}
break;
}
case 'rated': {
result.type = args[2] || 'rated';
break;
}
case 'switch': {
if (!inThis) {
reject(new Error("Expected switch after player."));
return;
}
if (args[2].startsWith(inThis + 'a: ')) {
const mon = args[3].split(', ')[0].split('-')[0];
output.team[mon].species = args[3].split(', ')[0];
output.team[mon].nick = args[2].split(inThis + 'a: ')[1];
}
break;
}
case 'move': {
if (!inThis) {
reject(new Error("Expected move after player."));
return;
}
if (args[2].startsWith(inThis + 'a: ')) {
if (output.team[args[2].split(inThis + 'a: ')[1]]) {
output.team[args[2].split(inThis + 'a: ')[1]].moves.push(args[3]);
} else {
// eslint-disable-next-line max-len
Object.values(output.team).find(m => m.nick === args[2].split(inThis + 'a: ')[1]).moves.push(args[3]);
}
}
break;
}
case 'win': {
result.win = id === toID(args[2]);
break;
}
case 'raw': {
// eslint-disable-next-line max-len
const match = args.join('|').match(/^\|raw\|(.*?)'s rating: (\d{4}) → <strong>(\d{4})<\/strong><br \/>\([+-]\d{1,2} for (?:winn|los)ing\)\s*$/);
if (match && toID(match[1]) === id) {
result.rating[0] = parseInt(match[2]);
result.rating[1] = parseInt(match[3]);
result.LL = true;
}
break;
}
}
}
resolve(result);
});
} catch (e) {
Bot.log(e);
Bot.log(output);
}
}).catch(error => {
Bot.log(error);
Bot.log(replay);
});
})).then(res => {
let valid = true;
function inValid (text) {
valid = false;
return text;
}
Object.keys(output.team).forEach(mon => output.team[mon].moves = [... new Set(output.team[mon].moves)]);
Bot.log(res);
// eslint-disable-next-line max-len
message.channel.send("```\n" + res.sort((a, b) => a.id - b.id).map((term, index, arr) => `${term.win ? "W" : "L"} | ${term.rating[0] || '----'} - ${term.rating[1] || '----'} | ${term.rated === "rated" ? term.rated || "Unrated " : "Rated "} | ${term.rating[0] && index && arr[index - 1][1] && term.rating[0] !== arr[index - 1][1] ? inValid("Elo didn't match properly.") : term.oppSize < 3 ? "Opponent had " + term.oppSize + " Pokemon." : ''}`).join('\n') + "```");
// eslint-disable-next-line max-len
message.channel.send("```\n" + `${output.username}: \n\nTeam: \n${Object.keys(output.team).map(m => `${output.team[m].species || m}: ${output.team[m].moves.sort().join(' / ')}${output.team[m].level === 100 ? '' : ` | Lv${output.team[m].level}`}`).join('\n')}\n\nAvatar: ${output.avatar}` + "\n```");
// message.channel.send("```\n" + require('util').inspect(output, true, 7) + "```");
let W = 0, L = 0;
res.forEach(match => {
if (match.type === "rated" && match.oppSize === 3) {
if (!match.win) L++;
else if (match.rating[0] >= 1100 || match.rating[1] >= 1100 && match.win) W++;
}
});
if (valid) message.channel.send(`Summary: ${W}-${L}`);
}).catch(err => {
Bot.log(err);
Bot.log(require('util').inspect(output, true, 7));
});
});
}).catch(Bot.log);
}
};
<file_sep>/commands/global/summarize.js
module.exports = {
cooldown: 100,
help: `Summarizes PS! battles.`,
permissions: 'coder',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `BLANK`);
}
};
<file_sep>/pmcommands/help.js
module.exports = {
help: `Displays the help for a specific command. Syntax: ${prefix}help (command)`,
permissions: 'locked',
commandFunction: function (Bot, by, args, client) {
if (!args[0]) {
// eslint-disable-next-line max-len
return Bot.pm(by, 'I\'m a Bot by PartMan. If you have any issues regarding me, please contact them. To see my usable commands, use ``' + prefix + 'commands`` in a chatroom.');
}
const name = tools.pmCommandAlias(args.join(''));
fs.readdir('./pmcommands', (err, files) => {
if (err) {
Bot.pm(by, e.message);
return Bot.log(e);
}
if (!files.includes(name + '.js')) return Bot.pm(by, `It doesn't look like that command exists...`);
const cReq = require(`./${name}.js`);
if (cReq && !tools.hasPermission(by, cReq.permissions)) return Bot.pm(by, 'Shh.');
if (!cReq.help) return Bot.pm(by, 'The help for that command wasn\'t found...');
return Bot.pm(by, cReq.help);
});
}
};
<file_sep>/pmcommands/tourpoll.js
module.exports = {
help: `Casts a vote for an ongoing tournament poll. Syntax: ${prefix}tourpoll vote (room), (tier)`,
noDisplay: true,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
switch (toID(args.shift())) {
case 'vote': {
let [room, tier] = args.join(' ').split(', ');
if (!tier) return Bot.pm(by, unxa);
room = tools.getRoom(room);
if (!Bot.rooms.hasOwnProperty(room)) return Bot.pm(by, `Sorry, I'm not in that room!`);
room = Bot.rooms[room];
tier = toID(tier);
if (!room.tourpoll) return Bot.pm(by, `That room doesn't have a tour poll active!`);
const user = toID(by), exist = room.tourpoll.votes[user];
const vote = room.tourpoll.options.find(opt => toID(opt) === tier);
if (!vote) return Bot.pm(by, `Invalid vote.`);
room.tourpoll.votes[user] = vote;
return Bot.roomReply(toID(room.title), by, `Your vote has been ${exist ? 'changed' : 'cast'} successfully.`);
}
default: return Bot.pm(by, this.help);
}
}
};
<file_sep>/commands/global/chesstest.js
module.exports = {
cooldown: 1,
help: `-_-`,
permissions: 'coder',
commandFunction: function (Bot, room, time, by, args, client) {
/* delete require.cache[require.resolve('../../data/chess.js')];
if (!Bot.rooms[room].chess) Bot.rooms[room].chess = new tools.Chess(toID(by), room);
let game = Bot.rooms[room].chess;
game.B.player = 'partman';
game.B.name = "PartMan";
game.W.player = '1v1lt61hupartm';
game.W.name = '1v1LT61HU PartM';
game.setBoard();
return Bot.say(room, `/adduhtml CHESS,${game.boardHTML(room, game.turn)}`);*/
}
};
<file_sep>/pmcommands/smogscrape.js
module.exports = {
help: `Scrapes a given Smogon thread replays of the given format. If a format is not specified, scrapes for all. DO NOT OVERUSE.`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
const key = "smogscrapeactive";
if (Bot[key]) return Bot.pm(by, "In use; please try again in 30 seconds.");
if (!args.length) return Bot.pm(by, unxa);
const message = args.join(' ');
const threadLink = message.match(/https?:\/\/www.smogon.com\/forums\/threads\/[a-z0-9-]+\.\d+\b/);
const format = message.match(/\bgen[1-8][a-z0-9]+\b/i);
if (!threadLink) return Bot.pm(by, "Unable to detect a valid Smogon thread.");
Bot.replayRegex = format ?
new RegExp(`(?:re)?play\\.pokemonshowdown\\.com\\/((?:smogtours-)?${toID(format[0])}-\\d+(?:-[a-z0-9]+pw)?)`, 'g') :
/(?:re)?play\.pokemonshowdown\.com\/((?:smogtours-)?gen[1-8][a-z0-9]+-\d+(?:-[a-z0-9]+pw)?)/g;
const mapF = rep => "" + rep.match(/[^/]+$/);
Bot[key] = { replays: [], pages: 0, pageNum: 0, threadLink: threadLink[0] };
Bot.pm(by, "Initiating scraper...");
new Promise((resolve, reject) => {
axios.get(Bot[key].threadLink).then(res => {
const matches = res.data.match(Bot.replayRegex);
if (matches) Bot[key].replays.push(...matches.map(mapF));
Bot[key].pages = res.data.match(/<li class="pageNav-page "><a href="\/[^"]+\/page-(\d+)">\1<\/a><\/li>/);
if (!Bot[key].pages) {
return resolve();
} else Bot[key].pages = Bot[key].pages[1];
Bot[key].pages = [parseInt(Bot[key.pages]), 30].reduce((a, b) => a > b ? a : b, 0);
function nextPage () {
Bot[key].pageNum++;
if (Bot[key].pageNum > Bot[key].pages) return resolve();
axios.get(`${Bot[key].threadLink}/page-${Bot[key].pageNum}`).then(resN => {
const matches = resN.data.match(Bot.replayRegex);
if (matches) Bot[key].replays.push(...matches.map(mapF));
nextPage();
});
}
nextPage();
}).catch(e => {
Bot.pm(by, "Something went wrong: " + e.message);
Bot.log(e);
reject();
});
}).then(() => {
Bot[key].replays = [...new Set(Bot[key].replays)];
// eslint-disable-next-line max-len
Bot.pm(by, `Done! From ${Bot[key].pages || '1'} page${Bot[key].pages ? 's' : ''}, I got ${Bot[key].replays.length} replays.`);
}).catch(e => {
Bot.pm(by, "Sorry, something went wrong. Replays I got were: ");
Bot.log(e);
}).finally(() => {
if (!Bot[key].replays.length) Bot.pm(by, "Oh, I didn't find any. ;-;");
// eslint-disable-next-line max-len
else Bot.serve(by, Bot[key].replays.sort().map(rep => `<a href="https://replay.pokemonshowdown.com/${rep}" target="_blank">https://replay.pokemonshowdown.com/${rep}</a>`).join('<br />'));
setTimeout(() => delete Bot[key], 0);
});
}
};
<file_sep>/pmcommands/editcommand.js
module.exports = {
help: `Edits a command using a pastebin link. Syntax: ${prefix}editcommand (command name), (room), (pastebin link)`,
permissions: 'admin',
commandFunction: function (Bot, by, args, client) {
return;
}
};
<file_sep>/commands/global/showpaste.js
module.exports = {
cooldown: 2000,
help: `Displays the content of a supplied pokepast.es link.`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args[0]) return Bot.say(room, unxa);
link = args.join(' ');
if (!/^https?:\/\/pokepast\.es\/[0-9a-z]+(?:\/json)?$/.test(link)) return Bot.say(room, 'Not a valid paste.');
require('request')(link.endsWith('/json') ? link : link + '/json', (error, response, body) => {
if (error) return;
let obj;
try {
obj = JSON.parse(body);
} catch (e) {
return Bot.pm(by, 'Invalid paste.');
}
let pkmn = obj.paste.match(/(?:^|\r?\n\r?\n)([^\r\n]*?)\r?\n/g);
if (!pkmn) return;
pkmn = pkmn
.map(m => {
m = m.trim();
const l = m.match(/\([^\(\)]+\)/g);
if (!l) return m.split('@')[0].trim();
else if (l.length === 2) return m.match(/\(.*?\)/)[0].substr(1).slice(0, -1);
else if (l.length === 1 && /\([MF]\)/.test(m)) return m.split(/\([MF]\)/)[0].trim();
else if (l.length === 1) return m.match(/\(.*?\)/)[0].substr(1).slice(0, -1);
else return m.split('@')[0].trim();
})
.map(m => m.toLowerCase().replace(/[^a-z0-9-]/g, ''))
.filter(m => data.pokedex[toID(m)] || data.pokedex[m.split('-')[0]])
.map(m => data.pokedex[toID(m)] ? toID(m) : m);
pkmn = pkmn.map(m => `<psicon pokemon="${m}" style="veritcal-align: middle;">`).join('');
// eslint-disable-next-line max-len
Bot.say(room, '/adduhtml POKEPASTE,<details><summary>' + obj.title + ' [' + pkmn + ']</summary><hr><br>' + obj.paste.replace(/\n/g, '<br>') + '</details>');
});
}
};
<file_sep>/discord/imanerd.js
/* eslint-disable no-unreachable */
module.exports = {
help: `Adds the Nerd role.`,
guildOnly: "750048485721505852",
commandFunction: function (args, message, Bot) {
return message.channel.send("Hi, nerd!").then(msg => msg.delete({ timeout: 3000 }));
Bot.log(message.author.username);
message.member.roles.add(message.guild.roles.cache.get("771591913332539414")).then(() => {
message.delete({ timeout: 100 }).then(() => {
message.channel.send("Added.").then(msg => msg.delete({ timeout: 3000 }));
});
}).catch(Bot.log);
}
};
<file_sep>/commands/botdevelopment/hplg.js
module.exports = {
cooldown: 1,
help: `Generates the HPL page.`,
permissions: 'coder',
commandFunction: function (Bot, room, time, by, args, client) {
delete require.cache[require.resolve('../../data/DATA/hpl-week7.json')];
const data = require('../../data/DATA/hpl-week7.json');
const html = fs.readFileSync('./pages/hplt.html', 'utf8');
const info = Object.keys(data).map(batch => {
const names = batch.split(' vs ');
const stuff = data[batch];
const scores = [0, 0];
Object.values(stuff.tiers).forEach(tier => {
if (tier[2][0] > tier[2][1]) scores[0]++;
else if (tier[2][1] > tier[2][0]) scores[1]++;
});
// eslint-disable-next-line max-len
return `<table><tr><th colspan="6" style="background: ${stuff.colours[0]}; color: ${stuff.colours[1]};"><img src="${stuff.sprites[0]}" height="30px" width="30px" style="vertical-align: middle;" /> ${names[0]} (${scores[0]})</th><th class="vs">vs</th><th colspan="6" style="background: ${stuff.colours[2]}; color: ${stuff.colours[3]};"><img src="${stuff.sprites[1]}" height="30px" width="30px" style="vertical-align: middle;" /> ${names[1]} (${scores[1]})</th></tr><tr><td class="hidden"> </td><td class="hidden"> </td><td class="hidden"> </td><td class="hidden"> </td><td class="hidden"> </td><td class="hidden"> </td><td class="vs"> </td><td class="hidden"> </td><td class="hidden"> </td><td class="hidden"> </td><td class="hidden"> </td><td class="hidden"> </td><td class="hidden"> </td></tr>${Object.keys(stuff.tiers).map(tier => {
const name = tier;
tier = stuff.tiers[tier];
// eslint-disable-next-line max-len
return `<tr><td class="tier" colspan="2">${name}</td><td class="player" colspan="4">${tools.colourize(tier[0])}</td><td class="vs">${tier[2].reduce((a, b) => a + b, 0) ? tier[2][0] : ''}-${tier[2].reduce((a, b) => a + b, 0) ? tier[2][1] : ''}</td><td class="player" colspan="4">${tools.colourize(tier[1])}</td><td class="matches" colspan="2">${tier[3].map((replay, index) => replay ? replay === "act" ? "<strong>ACTIVITY</strong>" : `<a href="${replay}" target="_blank"><button>${index + 1}</button></a>` : `<button onclick="window.alert('Not uploaded.')">${index + 1}</button>`).join('')}</td></tr>`;
}).join('')}</table>`;
}).join('<br/><br/>');
fs.writeFile('./pages/hpl/week7.html', html.replace(/INFO/, info), e => e ? Bot.log(e) : Bot.say(room, ":thumbs:"));
}
};
<file_sep>/commands/pokemongo/shinyupdate.js
module.exports = {
cooldown: 0,
help: `Updates PartBot's internal shiny list`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client, isPM) {
const URLS = {
names: 'https://raw.githubusercontent.com/Rplus/Pokemon-shiny/master/assets/name.json',
shinies: ''
};
const formes = {
_61: '-Alola',
_31: ['-Galar', 'Unown']
};
}
};
<file_sep>/data/GAMES/scrabble.js
const WORDS = require('../WORDS/index.js');
class Scrabble {
constructor (...input) {
const [id, room, restore] = input;
this.id = id;
this.room = room;
this.started = false;
this.boardTemplate = [
["TW", "-", "-", "DL", "-", "-", "-", "TW", "-", "-", "-", "DL", "-", "-", "TW"],
["-", "DW", "-", "-", "-", "TL", "-", "-", "-", "TL", "-", "-", "-", "DW", "-" ],
["-", "-", "DW", "-", "-", "-", "DL", "-", "DL", "-", "-", "-", "DW", "-", "-" ],
["DL", "-", "-", "DW", "-", "-", "-", "DL", "-", "-", "-", "DW", "-", "-", "DL"],
["-", "-", "-", "-", "DW", "-", "-", "-", "-", "-", "DW", "-", "-", "-", "-" ],
["-", "TL", "-", "-", "-", "TL", "-", "-", "-", "TL", "-", "-", "-", "TL", "-" ],
["-", "-", "DL", "-", "-", "-", "DL", "-", "DL", "-", "-", "-", "DL", "-", "-" ],
["TW", "-", "-", "DL", "-", "-", "-", "★", "-", "-", "-", "DL", "-", "-", "TW"],
["-", "-", "DL", "-", "-", "-", "DL", "-", "DL", "-", "-", "-", "DL", "-", "-" ],
["-", "TL", "-", "-", "-", "TL", "-", "-", "-", "TL", "-", "-", "-", "TL", "-" ],
["-", "-", "-", "-", "DW", "-", "-", "-", "-", "-", "DW", "-", "-", "-", "-" ],
["DL", "-", "-", "DW", "-", "-", "-", "DL", "-", "-", "-", "DW", "-", "-", "DL"],
["-", "-", "DW", "-", "-", "-", "DL", "-", "DL", "-", "-", "-", "DW", "-", "-" ],
["-", "DW", "-", "-", "-", "TL", "-", "-", "-", "TL", "-", "-", "-", "DW", "-" ],
["TW", "-", "-", "DL", "-", "-", "-", "TW", "-", "-", "-", "DL", "-", "-", "TW"]
];
this.board = tools.deepClone(this.boardTemplate);
this.placed = this.board.map(row => row.map(() => null));
this.players = {};
this.order = [];
this.bag = [];
this.letters = {
A: 9,
B: 2,
C: 2,
D: 4,
E: 12,
F: 2,
G: 3,
H: 2,
I: 9,
J: 1,
K: 1,
L: 4,
M: 2,
N: 6,
O: 8,
P: 2,
Q: 1,
R: 6,
S: 4,
T: 6,
U: 4,
V: 2,
W: 2,
X: 1,
Y: 2,
Z: 1,
" ": 2
};
this.points = {
A: 1,
B: 3,
C: 3,
D: 2,
E: 1,
F: 4,
G: 2,
H: 4,
I: 1,
J: 8,
K: 5,
L: 1,
M: 3,
N: 1,
O: 1,
P: 3,
Q: 10,
R: 1,
S: 1,
T: 1,
U: 1,
V: 4,
W: 4,
X: 8,
Y: 4,
Z: 10,
" ": 0
};
this.colours = {
'-': `#CCC5A8`,
DL: `#C0D5D0`,
TL: `#489AAB`,
DW: `#F8B7A2`,
TW: `#FF6251`,
letter: `#FFCC66`,
blank: `#555555`
};
Object.keys(this.letters).forEach(letter => this.bag.push(...Array.from({ length: this.letters[letter] }, () => letter)));
this.bag.shuffle();
this.spectators = [];
if (restore) Object.keys(restore).forEach(key => this[key] = restore[key]);
if (this.modded) this.mod(this.modded);
}
start () {
return new Promise((resolve, reject) => {
if (this.started) return reject(new Error(`Already started!`));
this.order = Object.keys(this.players).shuffle();
if (this.order.length > 4 || this.order.length < 2) return reject(new Error(`Invalid player count ${this.order.length}`));
this.turn = 0;
this.started = true;
this.order.forEach(player => this.getPlayer(player).tiles.push(...this.bag.splice(0, 7)));
this.passCount = 0;
return resolve();
});
}
getPlayer (context) {
if (typeof context === 'number' && this.order.length && this.order[context]) return this.players[this.order[context]];
return this.players[context?.id || toID(context)];
}
addPlayer (name) {
return new Promise((resolve, reject) => {
if (this.started) return reject('Already started');
const id = toID(name);
if (this.players[id]) return reject('Already a player');
if (Object.keys(this.players).length >= 4) return reject('4 players already playing');
this.players[id] = {
id: id,
name: name,
tiles: [],
score: 0
};
return resolve();
});
}
removePlayer (player) {
return new Promise((resolve, reject) => {
player = this.getPlayer(player);
if (!player) return reject('Player is not in the game');
if (this.started) {
const index = this.order.indexOf(player.id);
if (index < 0) return reject('Player has already forfeited/been DQed');
if (index <= this.turn) this.turn--;
this.bag.push(...player.tiles);
this.bag.shuffle();
this.order.splice(index, 1);
if (this.turn < 0) this.turn = this.order.length - 1;
this.passCount--;
}
delete this.players[player.id];
return resolve(this.started && this.order.length === 1);
});
}
isTurn (user) {
return toID(user) === this.getPlayer(this.turn)?.id;
}
checkWord (word) {
return WORDS.checkWord(word, this.dict, this.modded);
}
play (start, down, word) {
return new Promise((resolve, reject) => {
if (!this.started) return reject('Not started');
if (start[0] < 0 || start[0] >= 15 || start[1] < 0 || start[1] >= 15) return reject(`Invalid dimensions ${start}`);
word = word.toUpperCase().replace(/[^A-Z']/g, '').replace(/[A-Z]'/g, m => m[0].toLowerCase()).replace("'", '');
down = down ? 1 : 0;
const right = down ? 0 : 1;
const final = [start[0] + down * (word.length - 1), start[1] + right * (word.length - 1)];
if (final[0] < 0 || final[0] >= 15 || final[1] < 0 || final[1] >= 15) {
return reject(`What NO GOING OFF THE BOARD please kthx`);
}
const tiles = tools.deepClone(this.placed), placed = [];
const playedLetters = [];
for (let i = 0; i < word.length; i++) {
const x = start[0] + i * down;
const y = start[1] + i * right;
if (this.placed[x][y]) continue;
tiles[x][y] = word.charAt(i);
playedLetters.push(word.charAt(i).toUpperCase() === word.charAt(i) ? word.charAt(i) : ' ');
placed.push(`${x},${y}`);
}
if (!placed.length) return reject('Must play at least one letter');
const hand = this.getPlayer(this.turn).tiles.slice(), playedClone = playedLetters.slice();
let tmp;
while (playedClone.length) {
if (!hand.remove(tmp = playedClone.shift())) return reject(`Insufficient tiles for: ${tmp}`);
}
const temp = tools.deepClone(this.board);
let wordPlaces = new Set();
let connected = false;
placed.forEach(inf => {
inf = inf.split(',').map(num => ~~num);
let [x, y] = inf;
if (!connected) for (let i = -1; i <= 1; i++) for (let j = -1; j <= 1; j++) {
// check if connected
if (i || j) if (!(i && j)) if (tiles[x + i]?.[y + j] && !placed.includes([x + i, y + j].join(','))) {
connected = true;
}
}
temp[x][y] = '-';
while (tiles[x - 1]?.[y]) x--;
const x1 = x;
x = inf[0];
while (tiles[x + 1]?.[y]) x++;
const x2 = x;
x = inf[0];
while (tiles[x]?.[y - 1]) y--;
const y1 = y;
y = inf[1];
while (tiles[x]?.[y + 1]) y++;
const y2 = y;
y = inf[1];
const hor = [], ver = [];
for (let i = x1; i <= x2; i++) ver.push([i, y]);
for (let j = y1; j <= y2; j++) hor.push([x, j]);
if (hor.length > 1) wordPlaces.add(hor.map(cell => cell.join(',')).join('|'));
if (ver.length > 1) wordPlaces.add(ver.map(cell => cell.join(',')).join('|'));
});
if (!connected && !(this.board[7][7] === '★' && temp[7][7] === '-')) return reject('Not connected');
wordPlaces = [...wordPlaces];
const iScores = wordPlaces.map(wordSet => {
const coords = wordSet.split('|').map(set => set.split(',').map(n => ~~n));
const word = coords.map(coord => tiles[coord[0]][coord[1]]).join('');
const bonus = this.checkWord(word);
if (!bonus) return reject(`Invalid word: ${toID(word).toUpperCase()}`);
let mult = 1;
let thisc = 0;
coords.forEach(coord => {
const bSq = this.board[coord[0]][coord[1]], tile = tiles[coord[0]][coord[1]];
let selfMult = 1;
switch (bSq) {
case 'DW': case '★': mult *= 2; break;
case 'TW': mult *= 3; break;
case 'DL': selfMult = 2; break;
case 'TL': selfMult = 3; break;
case '-': break;
}
thisc += tile === tile.toUpperCase() ? selfMult * this.points[tile] : 0;
// Lowercase tiles are blanks
});
thisc *= mult;
if (typeof bonus === 'number') thisc *= bonus;
else if (Array.isArray(bonus)) thisc = Number(thisc * bonus[0] + bonus[1]);
return thisc;
});
let score = iScores.reduce((a, b) => a + b, 0);
if (!score) return reject('The first word must be at least two tiles long');
const player = this.getPlayer(this.turn), bingo = playedLetters.length === 7;
if (bingo) score += 50;
player.score += score;
this.board = temp;
this.placed = tiles;
while (playedLetters.length) player.tiles.remove(playedLetters.shift());
const receivedTiles = [];
while (player.tiles.length < 7 && this.bag.length) {
receivedTiles.push(this.bag[0]);
player.tiles.push(this.bag.shift());
}
this.nextTurn();
return resolve([player.name, score, iScores, bingo, receivedTiles]);
});
}
exchange (letters) {
return new Promise((resolve, reject) => {
if (!this.started) return reject('Hasn\'t started');
const player = this.getPlayer(this.turn);
if (typeof letters === 'string') letters = letters.toUpperCase().replace(/[^A-Z ]/g, '').split('');
const clone = player.tiles.slice();
if (this.bag.length < 7) {
return reject(`Not enough letters in the bag (there must be at least 7 tiles in the bag to exchange letters)`);
}
for (const letter of letters) {
if (!clone.remove(letter)) return reject(`Insufficient tiles of ${letter}`);
}
letters.forEach(letter => player.tiles.remove(letter));
const newLetters = this.bag.splice(0, letters.length);
this.bag.push(...letters);
this.bag.shuffle();
player.tiles.push(...newLetters);
return resolve([letters, newLetters]);
});
}
nextTurn (pass) {
delete this.getPlayer(this.turn).selected;
if (pass) this.passCount++;
else this.passCount = 0;
if (this.passCount > this.order.length) return true;
this.turn = (this.turn + 1) % this.order.length;
Object.values(this.players).forEach(player => {
delete player.selected;
delete player.exchange;
});
}
deduct () {
Object.values(this.players).forEach(player => {
player.score -= tools.scrabblify(player.tiles.join(''));
});
}
mod (mod) {
mod = toID(mod);
let modifier = Object.keys(WORDS.mods).find(k => k === mod);
if (!modifier) modifier = Object.keys(WORDS.mods).find(k => WORDS.mods[k].aliases?.includes(mod));
if (modifier) return this.modded = modifier;
else return false;
}
log () {
return this.placed.map(row => row.map(char => char || ' ').join('')).join('\n');
}
headerHTML (player) {
if (this.ended) return `<center><h2>Game ended</h2></center>`;
player = this.getPlayer(player);
const turn = this.getPlayer(this.turn);
if (player === turn) return `<center><h1>Your turn!</h1></center>`;
else return `<center><h2>${tools.colourize(turn.name)}'s turn</h2></center>`;
}
boardHTML (player) {
player = this.getPlayer(player) === this.getPlayer(this.turn);
let html = `<div style="min-height:40%;max-height:70%;overflow-y:scroll;"><table align="center" border="2">`;
for (let i = 0; i < 15; i++) {
html += '<tr>';
for (let j = 0; j < 15; j++) {
let isNotBlank;
// eslint-disable-next-line max-len
const button = `<button name="send" style="border:none;background:none;height:20px;width:20px;padding:0;" value="/w ${Bot.status.nickName},${prefix}scrabble ${this.room} c ${this.id} ${i} ${j}">`;
const split = (this.getPlayer(this.turn)?.selected || ',').split(',');
const selected = this.started && (i === parseInt(split[0]) && j === parseInt(split[1]));
// eslint-disable-next-line max-len
if (this.placed[i][j]) html += `<td height="20" width="20" style="background:${this.colours.letter};color:${(isNotBlank = this.placed[i][j] === this.placed[i][j].toUpperCase()) ? 'black' : this.colours.blank};text-align:center;padding:0;${selected ? 'border:2px;border-style:outset;border-color:white;' : ''}">${player ? button : ''}<b style="font-size:16px;">${this.placed[i][j].toUpperCase()}<sub style="font-size:0.4em;">${isNotBlank ? this.points[this.placed[i][j]] : 0}</sub></b>${player ? '</button>' : ''}</td>`;
// eslint-disable-next-line max-len
else if (i === 7 && j === 7) html += `<td height="20" width="20" style="background:${this.colours.DW};color:black;text-align:center;padding:0;${selected ? 'border:2px;border-style:outset;border-color:white;' : ''}">${player ? button : ''}<b style="font-size:16px;">★</b>${player ? '</button>' : ''}</td>`;
// eslint-disable-next-line max-len
else html += `<td height="20" width="20" style="background:${this.colours[this.board[i][j]]};${selected ? 'border:2px;border-style:outset;border-color:white;' : ''}">${player ? button + '</button>' : ''}</td>`;
}
html += '</tr>';
}
html += '</table></div>';
return html;
}
menuHTML (player) {
let html = '<div style="vertical-align:middle;text-align:center;">';
player = this.getPlayer(player);
const isTurn = player === this.getPlayer(this.turn);
if (isTurn && !this.ended) {
// eslint-disable-next-line max-len
if (player.exchange) html += `<div style="display:inline-block;width:70%;border:1px solid;padding:10px;margin:20px;"><form data-submitsend="/w ${Bot.status.nickName},${prefix}scrabble ${this.room} exchange ${this.id} {exchange}">Which letters would you like to exchange? <input type="text" name="exchange" width="100px" style="margin-right:20px;" placeholder="Tiles go here"/><input type="submit" value="Exchange!"/></form></div>`;
// eslint-disable-next-line max-len
else html += `<div style="display:inline-block;width:70%;border:1px solid;padding:10px;margin:20px;"><form data-submitsend="/w ${Bot.status.nickName},${prefix}scrabble ${this.room} play ${this.id} ${player.selected} {dir} {play}"><input type="radio" name="dir" value="down" id="rdw" required/><label for="rdw">Down</label> <input type="radio" name="dir" value="right" id="rrg"/><label for="rrg">Right</label><br/><input type="text" name="play" width="100px" style="margin-right:20px;" placeholder="Type your word here" required/><input type="submit" value="Play!"/></form></div>`;
html += '<br/>';
}
// eslint-disable-next-line max-len
html += `<div style="display:inline-block;width:250px;border:1px solid;margin-top:5%;padding-bottom:10px;margin-right:20px;"><h2>Your Tiles</h2>${player.tiles.map(tile => `<div height="20px" style="background:${this.colours.letter};color:black;text-align:center;padding:0;display:inline-block;margin:auto;min-width:20px;max-width:20px;"><b style="font-size:16px;">${tile === ' ' ? ' ' : tile}<sub style="font-size:0.4em;">${this.points[tile] || 0}</sub></b></div>`).join(' ')}</div>`;
// eslint-disable-next-line max-len
if (isTurn && !this.ended) html += `<div style="display:inline-block;width:150px;border:1px solid;padding:10px;margin:20px;"><button name="send" value="/w ${Bot.status.nickName},${prefix}scrabble ${this.room} pass ${this.id}" style="margin:auto;">Pass</button><br/><button name="send" value="/w ${Bot.status.nickName},${prefix}scrabble ${this.room} ${player.exchange ? 'close' : 'open'}exchange ${this.id}" style="margin:auto;">${player.exchange ? 'Go Back' : 'Exchange'}</button></div>`;
html += '</div>';
return html;
}
pointsHTML () {
// eslint-disable-next-line max-len
return `<div style="max-height:100px;border:1px solid;padding:30px;">${this.order.map(u => this.getPlayer(u)).map(u => `${tools.colourize(u.name + ':')} ${u.score}`).join('<br/>')}</div>`;
}
HTML (user) {
const player = this.getPlayer(user);
if (player) {
// eslint-disable-next-line max-len
return `/sendhtmlpage ${player.name},SCRABBLE + ${this.room} + ${this.id},${this.headerHTML(player)}${this.boardHTML(player)}${this.menuHTML(player)}${this.pointsHTML()}`;
// eslint-disable-next-line max-len
} else return `/sendhtmlpage ${user},SCRABBLE + ${this.room} + ${this.id},${this.headerHTML()}${this.boardHTML()}${this.pointsHTML()}`;
}
highlight () {
return this.started ? `/highlighthtmlpage ${this.order[this.turn]}, SCRABBLE + ${this.room} + ${this.id}, Your turn!` : '';
}
}
module.exports = Scrabble;
<file_sep>/commands/global/j.js
module.exports = {
cooldown: 1,
help: `Joins a game in signups.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
// This should probably be phased out of usage
if (Bot.rooms[room].blackjack) return require('./blackjack.js').commandFunction(Bot, room, time, by, ['join'], client);
if (Bot.rooms[room].ev) return require('./explodingvoltorb.js').commandFunction(Bot, room, time, by, ['join'], client);
if (Bot.rooms[room].CR) return require('./chainreaction.js').commandFunction(Bot, room, time, by, ['join'], client);
}
};
<file_sep>/commands/hindi/answer.js
module.exports = {
cooldown: 1,
help: `Event ke wakt iss command se answer karna hai - \`\`${prefix}answer (aapka answer)\`\``,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
function score (name, index) {
let points;
const username = Bot.rooms[room].users.find(u => toID(u) === name).substr(1);
// console.log(name, Bot.rooms[room].users);
tools.addPoints(0, username, points = index > 3 ? 2 : 5 - index, 'groupchat-hindi-event').then(() => {
Bot.pm(name, `Aapko ${points} points mile!`);
}).catch(err => {
Bot.pm(name, err.message);
Bot.log(err);
Bot.pm(name, points);
});
return username + ` [${points}]`;
}
const info = Bot.rooms[room].event;
if (!info) return Bot.pm(by, "Event filhaal nahi chal raha...");
if (!info.sol) return Bot.pm(by, "Sabar karo zaraa...");
if (!info.active) return Bot.pm(by, "Late ;-;");
const id = toID(by);
const ans = toID(args.join(''));
const sol = toID(info.sol);
const offset = require('js-levenshtein')(ans, sol);
if (offset > 1) return Bot.pm(by, `Aapka answer galat tha. ;-;`);
if (!info.solved.length) {
info.timer = setTimeout(() => {
info.active = false;
Bot.say(room, `/wall Time khatm! Winners the: ${tools.listify(info.solved.map(score))}`);
Bot.log(info.solved);
info.solved = [];
clearTimeout(info.dqTimer);
Bot.say('groupchat-hindi-event', "Next");
}, 3000);
} else if (info.solved.includes(id)) return Bot.pm(by, "Aapne already answer kiya hai...");
info.solved.push(id);
Bot.pm(by, "Aapka jawaab sahi hai!");
}
};
<file_sep>/pmcommands/whisper.js
module.exports = {
help: `PMs a user. Syntax: ${prefix}whisper (user), (message)`,
permissions: 'admin',
commandFunction: function (Bot, by, args, client) {
const a = args.join(' ').split(',');
if (!a[0]) return Bot.pm(by, unxa);
return Bot.pm(a.shift(), a.join(','));
}
};
<file_sep>/data/VR/TC7/fire.js
exports.fire = {
sp: [],
s: ["Blaziken-Mega", "Incineroar"],
sm: [],
ap: [],
a: ["Charizard-Mega-X"],
am: [],
bp: ["Blaziken", "Darmanitan", "Marowak-Alola", "Victini "],
b: ["Emboar", "Silvally-Fire", "Entei"],
bm: ["Infernape", "Talonflame", "Heatran", "Camerupt"],
cp: ["Blacephalon", "Numel"],
c: ["Houndoom-Mega", "Delphox"],
cm: ["Charizard-Mega-Y", "Rotom-Heat", "Volcarona", ""],
d: ["Torkoal", "Magcargo"],
e: [" Salazzle", "Chandelure"],
unt: ["Turtonator"],
bans: ["Volcanion", "Cameruptite"]
};
<file_sep>/commands/global/fixname.js
module.exports = {
cooldown: 100000,
help: `Fixes the Bot's nickname in memory.`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `My name is now ${Bot.status.nickName = config.nickName}!`);
// This is gonna be awkward in the public repo
}
};
<file_sep>/pmcommands/ppw.js
module.exports = {
help: `Piplupede stuff`,
permissions: 'none',
noDisplay: true,
commandFunction: function (Bot, by, args, client) {
// eslint-disable-next-line max-len
const html = tools.quoteParse(`[15:33:03] @MC PrincessPearl~: It’s the cool kids club\n[15:33:09] @MC PrincessPearl~: Aka friends of swiff all in one gc`);
Bot.say('piplupede', `/sendprivatehtmlbox ${by}, ${html}`);
}
};
<file_sep>/commands/hindi/hpl.js
module.exports = {
cooldown: 1,
help: `HPL ka score dikhaata hai`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
const html = fs.readFile('./data/DATA/hplboard.html', 'utf8', (err, html) => {
if (err) Bot.pm(by, err);
Bot.say(room, `/adduhtml HPLBOARD, ${html}`);
});
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/cast.js
module.exports = {
cooldown: 1000,
help: `Allows you to cast a vote for an ongoing Blitz. Syntax: ${prefix}cast (option)`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
if (!Bot.rooms[room].blitzObject) return Bot.say(room, 'No Blitz is currently active.');
if (Bot.rooms[room].blitzObject.prepping) return Bot.say(room, 'Whoa, hold your horses! The Blitz hasn\'t started, yet!');
if (!Bot.rooms[room].blitzObject.active) return Bot.say(room, 'No Blitz is currently active.');
if (!args[0] || args[1]) return Bot.say(room, unxa);
const vote = args[0].toLowerCase();
if (!typelist.includes(vote)) return Bot.say(room, 'Invalid type.');
if (!Bot.rooms[room].blitzObject.autostart) {
delete Bot.rooms[room].blitzObject;
return Bot.say(room, `${by.substr(1)} won the Blitz with ${tools.toName(vote)}!`);
}
if (!Bot.rooms[room].blitzObject.official) {
if (Bot.rooms[room].blitzObject.gen == 7) require('./tc7.js').commandFunction(Bot, room, time, Bot.rooms[room].blitzObject.starter, [vote], client);
else if (Bot.rooms[room].blitzObject.gen == 8) require('./tc.js').commandFunction(Bot, room, time, Bot.rooms[room].blitzObject.starter, [vote], client);
delete Bot.rooms[room].blitzObject;
} else if (!Bot.rooms[room].blitzObject.official) {
if (Bot.rooms[room].blitzObject.gen == 7) require('./tc7.js').commandFunction(Bot, room, time, Bot.rooms[room].blitzObject.starter, [vote, 'official'], client);
else if (Bot.rooms[room].blitzObject.gen == 8) require('./tc.js').commandFunction(Bot, room, time, Bot.rooms[room].blitzObject.starter, [vote, 'official'], client);
delete Bot.rooms[room].blitzObject;
}
return;
}
};
<file_sep>/discord/randpoke.js
module.exports = {
help: `Random Pokemon! No filters work, but numbers do.`,
pm: true,
commandFunction: function (args, message, Bot) {
let num = 1;
if (!isNaN(parseInt(args.join('')))) num = parseInt(args.join(''));
const mons = Object.values(data.pokedex).filter(m => {
return m.num > 0 && !m.forme;
}).map(m => m.name).random(num).join(', ');
return message.channel.send('```' + mons + '```');
}
};
<file_sep>/discord/refundhint.js
const PZ = require('../data/PUZZLES/index.js');
module.exports = {
help: `Adds a hint to the specified team.`,
guildOnly: PZ.guildID,
commandFunction: function (args, message, Bot) {
if (!message.member.roles.cache.has(PZ.IDs.staff)) {
return message.channel.send('Access denied.').then(msg => msg.delete({ timeout: 3000 }));
}
if (!args.length) return message.channel.send("Which team?");
const team = PZ.getTeam(toID(args.join('')));
if (!team) return message.channel.send("Couldn't get the team you meant.");
PZ.addHints(team, 1).then(nam => {
message.channel.send(`Hint refunded! ${team.name} now has ${nam} hint(s).`);
}).catch(e => Bot.log(e));
}
};
<file_sep>/config.js
const debug = false;
exports.prefix = 'PREFIX_HERE';
exports.webPort = 8080;
exports.avatar = 'supernerd';
exports.nickName = 'USERNAME_HERE';
exports.pass = '<PASSWORD>';
exports.token = 'DISCORD_TOKEN_HERE'; // leave blank to disable Discord
exports.autoJoin = debug ? ['botdevelopment'] : ['botdevelopment']; // The second is the rooms to be joined normally
exports.status = false; // Set to a string if you want a status
exports.ignoreRooms = []; // Will be phased out
exports.websiteLink = `http://localhost:${exports.webPort}`; // Local address; IP addresses and hosted domains both work
exports.logRooms = []; // Do NOT use this without permission from a room owner
exports.owner = 'YOUR_USERNAME_HERE';
exports.discordAdmins = ['ADMIN_ID']; // Array of Discord IDs of administrators
exports.auth = {
admin: ['ADMIN_USERID_HERE'],
coder: [],
alpha: [],
beta: [],
gamma: [],
locked: []
};
exports.mongoURL = `mongodb://localhost:27017/PartBot`; // Put in a valid MongoDB URL here
<file_sep>/commands/groupchat-partbot-1v1tc/submitcolour.js
module.exports = {
cooldown: 1000,
help: `Submits a Type + Colour combination for the colourization of type-related stuff. Syntax: ${prefix}submitcolour (colour [hex code]), (type)`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
const cargs = args.join('').split(',');
if (!cargs[1]) return Bot.say(room, unxa);
let colour = cargs[0].toUpperCase().replace(/[^0-9A-F]/g, '');
if (!colour.length == 6) return Bot.say(room, 'Invalid colour hex.');
colour = '#' + colour;
const type = toID(cargs[1]);
if (!typelist.includes(type)) return Bot.say(room, 'Invalid type.');
fs.appendFileSync('./data/DATA/typecoloursubs.txt', '\n' + colour + ' : ' + type);
return Bot.say(room, 'Your submission has been logged. (' + colour + ' for ' + tools.toName(type) + ')');
}
};
<file_sep>/data/GAMES/lightsout.js
class LO {
constructor (room, user, size) {
this.name = user;
this.user = toID(user);
this.room = room.toLowerCase().replace(/[^a-z0-9-]/g, '');
this.size = size || [5, 5];
this.board = Array.from({ length: size[0] }).map(row => Array.from({ length: size[1] }).map(t => 0));
['soln', 'moves', 'spectators'].forEach(k => this[k] = []);
for (let i = 0; i < size[0]; i++) for (let j = 0; j < size[1]; j++) {
if (Math.random() < 0.5 || this.soln.length === 0 && i === size[0] - 1 && j === size[1] - 1) this.soln.push([i, j]);
}
this.click = (a, b) => {
if (!(a < this.size[0] && a >= 0 && b < this.size[1] && b >= 0)) return null;
this.board[a][b] = this.board[a][b] ? 0 : 1;
if (a) this.board[a - 1][b] = this.board[a - 1][b] ? 0 : 1;
if (b) this.board[a][b - 1] = this.board[a][b - 1] ? 0 : 1;
if (a + 1 < this.size[0]) this.board[a + 1][b] = this.board[a + 1][b] ? 0 : 1;
if (b + 1 < this.size[1]) this.board[a][b + 1] = this.board[a][b + 1] ? 0 : 1;
this.moves.push([a, b]);
if (!this.board.reduce((a, b) => a + b.reduce((c, d) => c + d, 0), 0)) return true;
return false;
};
this.soln.forEach(pair => this.click(...pair));
this.moves = [];
this.problem = tools.deepClone(this.board);
}
boardHTML (isPlayer, board, limit, colours = ["#6e6d62", "#fff9ba", "#111111"]) {
// eslint-disable-next-line max-len
return `<center${limit ? ` style="max-height: 200px; overflow-y: scroll;"` : ''}><table style="border:none;background:${colours[2]}">${(board || this.board).map((row, x) => `<tr>${row.map((bulb, y) => `<td>${isPlayer ? `<button name="send" value="/msgroom ${this.room},/botmsg ${Bot.status.nickName},${prefix}lo ${this.room}, c ${x} ${y}" style="background:none;border:none;padding:0">` : ''}<div style="height:${board ? '15' : '35'}px;width:${board ? '15' : '35'}px;background-image:radial-gradient(${colours[bulb]} 60%,#333333);border-radius:${board ? '3.75' : '10'}px;margin:${board ? '1.5' : '3'}px"></div>${isPlayer ? '</button>' : ''}</td>`).join('')}</tr>`).join('')}</table></center>`;
}
}
module.exports = LO;
<file_sep>/discord/stone.js
module.exports = {
help: `Displays the stats for a specified Mega Stone.`,
guildOnly: ['713967096949768213', '747809518741618788', '887887985629073459'],
commandFunction: function (args, message, Bot) {
const stone = toID(args.join(''));
if (!data.items[stone] || !data.items[stone].megaStone) return message.channel.send('Unrecognized stone.');
const stats = Object.values(data.pokedex[toID(data.items[stone].megaStone)].baseStats).map((t, i) => {
return t - Object.values(data.pokedex[toID(data.items[stone].megaEvolves)].baseStats)[i];
});
const statStr = ['HP', 'Atk', 'Def', 'SpA', 'SpD', 'Spe'].map((term, i) => term + ': ' + stats[i]).join(', ');
return message.channel.send('```' + statStr + '```');
}
};
<file_sep>/discord/submitchallenge.js
module.exports = {
help: `Submits a challenge`,
guildOnly: '',
commandFunction: function (args, message, Bot) {
const challenge = args.join(' ').replace(/@(?:everyone|here)/g, 'REDACTED PING');
if (!challenge) return message.channel.send('Type your challenge info, too!').then(msg => msg.delete({ timeout: 3000 }));
if (challenge.length > 1800) return message.channel.send('Type less stuff onegai').then(msg => msg.delete({ timeout: 3000 }));
client.channels.cache.get(ID).send(`Challenge from <@${message.author.id}>:\n\n\`\`\`\n${challenge}\n\`\`\``);
message.channel.send("It's been submitted!");
}
};
<file_sep>/pmcommands/filter.js
module.exports = {
cooldown: 1000,
help: `Filters through the Pokedex. \`\`dex\`\` is the Pokedex object, \`\`m\`\` is the Pokemon ID.`,
permissions: 'coder',
commandFunction: function (Bot, by, args, client) {
try {
let func = args.join(' ');
if (!func.includes('return')) func = 'return ' + func;
const filter = new Function(`return function (m, dex) {${func}}`)();
const out = Object.keys(data.pokedex).filter(m => filter(m, data.pokedex));
if (!out.length) return Bot.pm(by, 'None.');
// eslint-disable-next-line max-len
return Bot.sendHTML(by, `<DETAILS><SUMMARY>Results (${out.length})</SUMMARY>` + out.map(m => data.pokedex[m].name).sort().join('<BR>') + '</DETAILS>');
} catch (e) {
Bot.pm(by, e.message);
}
}
};
<file_sep>/commands/global/othello.js
function gameTimer (game, turn) {
const time = 60;
if (!Bot.rooms[game.room]) return;
if (!Bot.rooms[game.room].gameTimers) Bot.rooms[game.room].gameTimers = {};
const gameTimers = Bot.rooms[game.room].gameTimers;
clearTimeout(gameTimers[game.id]);
gameTimers[game.id] = setTimeout(() => Bot.say(game.room, `${turn} hasn't played for the past ${time} seconds...`), time * 1000);
}
function clearGameTimer (game) {
clearTimeout(Bot.rooms[game.room]?.gameTimers?.[game.id]);
}
function sendEmbed (room, winner, players, board, logs, scores) {
Bot.say(room, `http://partbot.partman.co.in/othello/${logs}`);
if (!['boardgames'].includes(room)) return;
const Embed = require('discord.js').MessageEmbed, embed = new Embed();
embed
.setColor('#008000')
.setAuthor('Othello - Room Match')
.setTitle((winner === 'W' ? `**${players.W}**` : players.W) + ' vs ' + (winner === 'B' ? `**${players.B}**` : players.B))
.setURL(`${websiteLink}/othello/${logs}`)
.addField(scores ? scores.join(' - ') : '\u200b', Object.values(board).map(row => row.map(cell => {
switch (cell) {
case 'B': return ':black_circle:';
case 'W': return ':white_circle:';
default: return ':green_circle:';
}
}).join('')).join('\n'));
client.channels.cache.get('576488243126599700').send(embed).catch(e => {
Bot.say(room, 'Unable to send the game to the Discord because ' + e.message);
Bot.log(e);
});
}
function runMoves (run, info, game) {
const room = game.room, id = game.id;
switch (run) {
case 'start': {
game.start();
Bot.say(room, `Othello: ${game.W.name} vs ${game.B.name} GOGO`);
// eslint-disable-next-line max-len
return game.spectatorSend(`<center><h1>${game[game.turn].name}'s Turn (${game.turn})</h1>${game.boardHTML()}</center>`).then(() => {
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.W.id}, Othello + ${room} + ${id}, ${game.turn === 'W' ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.B.id}, Othello + ${room} + ${id}, ${game.turn === 'B' ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
setTimeout(() => {
Bot.say(room, `/highlighthtmlpage ${game.W.id}, Othello + ${room} + ${id}, Your turn!`);
}, 1000);
// eslint-disable-next-line max-len
Bot.say(room, `/adduhtml OTHELLO-${id},<hr />${tools.colourize(game.W.name)} vs ${tools.colourize(game.B.name)}! <div style="text-align: right; display: inline-block; font-size: 0.9em; float: right;"><button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room} spectate ${id}">Watch!</button></div><hr />`);
});
}
case 'join': {
const { user, side } = info;
game[side].id = toID(user);
game[side].name = user.replace(/[<>]/g, '');
if (game.W.id && game.B.id) return runMoves('start', null, game);
// eslint-disable-next-line max-len
const html = `<hr /><h1>Othello Signups are active!</h1>${['W', 'B'].filter(side => !game[side].id).map(side => `<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room}, join ${id} ${side === 'W' ? 'White' : 'Black'}">${side === 'W' ? 'White' : 'Black'}</button>`).join(' ')}<hr />`;
return Bot.say(room, `/adduhtml OTHELLO-${id}, ${html}`);
}
case 'W': case 'B': {
game.spectatorSend(`<center><h1>${game[game.turn].name}'s Turn (${game.turn})</h1>${game.boardHTML()}</center>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.W.id}, Othello + ${room} + ${id}, ${game.turn === 'W' ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.B.id}, Othello + ${room} + ${id}, ${game.turn === 'B' ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
setTimeout(() => {
Bot.say(room, `/highlighthtmlpage ${game[game.turn].id}, Othello + ${room} + ${id}, Your turn!`);
}, 1000);
break;
}
case 'resign': {
clearGameTimer(game);
const loser = info, players = { W: game.W.name, B: game.B.name }, board = game.board, winner = loser === 'W' ? 'B' : 'W';
let logs = game.moves;
fs.unlink(`./data/BACKUPS/othello-${room}-${id}.json`, e => {});
Bot.say(room, `/adduhtml OTHELLO-${Date.now()},<center>${game.boardHTML()}</center>`);
game.spectatorSend(`<center><h1>Resigned.</h1>${game.boardHTML()}</center>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.W.id}, Othello + ${room} + ${id}, <center><h1>Resigned.</h1>${game.boardHTML(true)}</center>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.B.id}, Othello + ${room} + ${id}, <center><h1>Resigned.</h1>${game.boardHTML(true)}</center>`);
Bot.say(room, `${players[loser]} resigned.`);
logs += winner === 'W' ? 'Y' : 'Z';
delete Bot.rooms[room].othello[id];
return sendEmbed(room, winner, players, board, logs);
}
case 'forcedraw': {
clearGameTimer(game);
const players = { W: game.W.name, B: game.B.name }, board = game.board;
let logs = game.moves;
fs.unlink(`./data/BACKUPS/othello-${room}-${id}.json`, e => {});
Bot.say(room, `/adduhtml OTHELLO-${Date.now()},<center>${game.boardHTML()}</center>`);
game.spectatorSend(`<center><h1>Force-drawed</h1>${game.boardHTML()}</center>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.W.id}, Othello + ${room} + ${id}, <center><h1>Force-drawed</h1>${game.boardHTML(true)}</center>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.B.id}, Othello + ${room} + ${id}, <center><h1>Force-drawed</h1>${game.boardHTML(true)}</center>`);
Bot.say(room, `The game was forcefully drawn.`);
logs += '_';
delete Bot.rooms[room].othello[id];
return sendEmbed(room, 'O', players, board, logs);
}
default: {
clearGameTimer(game);
const info = JSON.parse(run);
const winner = info.winner, players = { W: game.W.name, B: game.B.name }, board = game.board, logs = game.moves;
fs.unlink(`./data/BACKUPS/othello-${room}-${id}.json`, e => {});
Bot.say(room, `/adduhtml OTHELLO-${Date.now()},<center>${game.boardHTML(false, true)}</center>`);
game.spectatorSend(`<center><h1>Game Ended.</h1>${game.boardHTML()}</center>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.W.id}, Othello + ${room} + ${id}, <center><h1>Game Ended.</h1>${game.boardHTML('W', true)}</center>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.B.id}, Othello + ${room} + ${id}, <center><h1>Game Ended.</h1>${game.boardHTML('B', true)}</center>`);
let wScore, bScore;
// eslint-disable-next-line max-len
Bot.say(room, `Game ended! ${game[winner] ? `${game[winner].name} won!` : 'It was a draw!'} ${wScore = board.reduce((accu, row) => accu + row.reduce((acc, cur) => cur === 'W' ? acc + 1 : acc, 0), 0)}W/${bScore = board.reduce((accu, row) => accu + row.reduce((acc, cur) => cur === 'B' ? acc + 1 : acc, 0), 0)}B`);
delete Bot.rooms[room].othello[id];
return sendEmbed(room, winner, players, board, logs, [wScore, bScore]);
}
}
fs.writeFile(`./data/BACKUPS/othello-${room}-${id}.json`, JSON.stringify(game), e => {
if (e) console.log(e);
});
}
module.exports = {
// eslint-disable-next-line max-len
help: `The Othello module. Use \`\`${prefix}othello new\`\` to make a game, and \`\`${prefix}othello spectate\`\` to watch. To resign, use \`\`${prefix}othello resign\`\`. Rules: https://www.worldothello.org/about/about-othello/othello-rules/official-rules/english`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client, isPM) {
if (!args[0]) args.push('help');
switch (args[0].toLowerCase()) {
case 'help': case 'h': {
if (tools.hasPermission(by, 'gamma', room) && !isPM) return Bot.say(room, this.help);
else Bot.roomReply(room, by, this.help);
break;
}
case 'new': case 'n': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (isPM) return Bot.roomReply(room, by, `Thou art stinky, do this in a chatroom`);
if (!tools.canHTML(room)) return Bot.say(room, 'I can\'t do that here. Ask an RO to promote me or something.');
if (!Bot.rooms[room].othello) Bot.rooms[room].othello = {};
const id = Date.now();
Bot.rooms[room].othello[id] = GAMES.create('othello', id, room);
// eslint-disable-next-line max-len
Bot.say(room, `/adduhtml OTHELLO-${id}, <hr/><h1>Othello Signups have begun!</h1><button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room}, join ${id} White">White</button><button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room}, join ${id} Black">Black</button><button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room}, join ${id} Random">Random</button><hr/>`);
// eslint-disable-next-line max-len
Bot.say(room, '/notifyrank all, Othello, A new game of Othello has been created!, A new game of Othello has been created.');
break;
}
case 'join': case 'j': {
if (!Bot.rooms[room].othello) return Bot.roomReply(room, by, 'There isn\'t an active Othello game in this room.');
if (!args[1]) return Bot.roomReply(room, by, 'Please specify the ID / side.');
const user = toID(by);
let id, side, rand = false;
if (args[2] && parseInt(args[1])) {
id = args[1];
side = args[2][0].toUpperCase();
if (side === 'R') {
side = ['W', 'B'].random();
rand = true;
}
if (!['W', 'B'].includes(side)) {
return Bot.roomReply(room, by, "I only accept white and black. (insert snarky comment)");
}
} else if (Object.keys(Bot.rooms[room].othello).length === 1) {
id = Object.keys(Bot.rooms[room].othello)[0];
side = args[1][0].toUpperCase();
if (side === 'R') {
side = ['W', 'B'].random();
rand = true;
}
if (!['W', 'B'].includes(side)) {
return Bot.roomReply(room, by, "I only accept white and black. (insert snarky comment)");
}
} else {
side = args[1][0].toUpperCase();
if (side === 'R') {
side = ['W', 'B'].random();
rand = true;
}
if (!['W', 'B'].includes(side)) {
return Bot.roomReply(room, by, "I only accept white and black. (insert snarky comment)");
}
id = Object.keys(Bot.rooms[room].othello).find(k => {
const game = Bot.rooms[room].othello[k];
return game && !game.started && !game[side].id;
});
if (!id) return Bot.roomReply(room, by, "Sorry, unable to find any open games.");
}
const game = Bot.rooms[room].othello[id];
if (!game) return Bot.roomReply(room, by, "Nope. BOOP");
if (game.started) return Bot.roomReply(room, by, 'Too late!');
if (game[side].id) return Bot.roomReply(room, by, "Sorry, already taken!");
const other = side === 'W' ? 'B' : 'W';
if (game[other].id === user) {
return Bot.roomReply(room, by, "~~You couldn't find anyone else to fight you? __Really__?~~");
}
// eslint-disable-next-line max-len
Bot.say(room, `${by.substr(1)} joined Othello (#${id}) as ${side === 'W' ? 'White' : 'Black'}!${rand ? ' (random)' : ''}`);
runMoves('join', { user: by.substr(1), side: side }, game);
break;
}
case 'play': case 'move': case 'click': {
if (!Bot.rooms[room].othello) return Bot.roomReply(room, by, 'There isn\'t an active Othello game in this room.');
if (!args[1]) return Bot.roomReply(room, by, unxa);
args.shift();
if (!Object.keys(Bot.rooms[room].othello).length) return Bot.roomReply(room, by, "No games are active.");
let id;
const user = toID(by);
if (args[0] && /^\d+$/.test(args[0].trim())) id = args.shift().trim();
else id = Object.keys(Bot.rooms[room].othello).find(k => {
const game = Bot.rooms[room].othello[k];
return game && game.started && !game[game.turn].id === user;
});
if (!id) return Bot.roomReply(room, by, "Unable to find the game you meant to play in.");
const game = Bot.rooms[room].othello[id];
if (!game) return Bot.roomReply(room, by, "Not a valid ID.");
if (!game.started) return Bot.roomReply(room, by, 'OI, IT HASN\'T STARTED!');
if (!(game[game.turn].id === toID(by))) return;
let coords = args.join('').split(',');
if (coords.length !== 2) {
return Bot.roomReply(room, by, "I need two coordinates to play - why not click on the board instead?");
}
coords = coords.map(t => parseInt(toID(t)));
if (isNaN(coords[0]) || isNaN(coords[1])) return Bot.roomReply(room, by, "Invalid coordinates. ;-;");
const canPlay = game.canPlay(...coords);
if (!canPlay) return Bot.roomReply(room, by, "Sorry, you can't play there!");
delete game.W.isResigning;
delete game.B.isResigning;
clearGameTimer(game);
gameTimer(game, game[game.turn === 'W' ? 'B' : 'W'].name);
game.play(coords[0], coords[1]);
runMoves(game.nextTurn(), null, game);
break;
}
case 'substitute': case 'sub': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].othello) return Bot.roomReply(room, by, 'This room does not have any Othello games.');
args.shift();
let id, cargs;
if (!Object.keys(Bot.rooms[room].othello).length) return Bot.roomReply(room, by, "No games are active.");
if (/^[^a-zA-Z]+$/.test(args[0])) id = toID(args.shift());
else if (Object.keys(Bot.rooms[room].othello).length === 1) id = Object.keys(Bot.rooms[room].othello)[0];
else {
cargs = args.join(' ').split(/\s*,\s*/);
if (cargs.length !== 2) return Bot.roomReply(room, by, "I NEED TWO NAMES GIVE ME TWO NAMES");
const id1 = toID(cargs[0]), id2 = toID(cargs[1]);
id = Object.keys(Bot.rooms[room].othello).find(k => {
const game = Bot.rooms[room].othello[k], ps = [game.W.id, game.B.id];
return game?.started && (ps.includes(id1) && !ps.includes(id2) || !ps.includes(id1) && ps.includes(id2));
});
}
cargs = args.join(' ').replace(/[<>]/g, '').split(/\s*,\s*/);
if (cargs.length !== 2) return Bot.roomReply(room, by, "I NEED TWO NAMES GIVE ME TWO NAMES");
if (!id) return Bot.roomReply(room, by, "Sorry, I couldn't find a valid game to sub.");
const game = Bot.rooms[room].othello[id];
if (!game.started) return Bot.roomReply(room, by, 'Excuse me?');
cargs = cargs.map(carg => carg.trim());
const users = cargs.map(carg => toID(carg));
if (
users.includes(game.W.id) && users.includes(game.B.id) ||
!users.includes(game.W.id) && !users.includes(game.B.id)
) return Bot.say(room, 'Those users? Something\'s wrong with those...');
if ([game.W.id, game.B.id].includes(toID(by)) && !tools.hasPermission(by, 'coder')) {
return Bot.say(room, "Hah! Can't sub yourself out.");
}
let ex, add;
if (users.includes(game.W.id)) {
if (users[0] === game.W.id) {
Bot.say(room, `${game.W.name} was subbed with ${cargs[1]}!`);
game.W.id = users[1];
game.W.name = cargs[1];
ex = users[0];
add = users[1];
} else {
Bot.say(room, `${game.W.name} was subbed with ${cargs[0]}!`);
game.W.id = users[0];
game.W.name = cargs[0];
ex = users[1];
add = users[0];
}
} else {
if (users[0] === game.B.id) {
Bot.say(room, `${game.B.name} was subbed with ${cargs[1]}!`);
game.B.id = users[1];
game.B.name = cargs[1];
ex = users[0];
add = users[1];
} else {
Bot.say(room, `${game.B.name} was subbed with ${cargs[0]}!`);
game.B.id = users[0];
game.B.name = cargs[0];
ex = users[1];
add = users[0];
}
}
game.spectators.remove(add);
game.spectators.push(ex);
runMoves(game.turn, null, game);
break;
}
case 'end': case 'e': {
if (!Bot.rooms[room].othello) return Bot.roomReply(room, by, 'This room does not have any Othello games.');
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
args.shift();
let id;
if (!Object.keys(Bot.rooms[room].othello).length) return Bot.roomReply(room, by, "No games are active.");
if (args.length && /^[^a-zA-Z]+$/.test(args.join(''))) id = toID(args.join(''));
else if (Object.keys(Bot.rooms[room].othello).length === 1) id = Object.keys(Bot.rooms[room].othello)[0];
else {
const cargs = args.join('').split(/(?:,|\s+v(?:er)?s(?:us)?\.?\s+)/).map(toID);
if (cargs.length !== 2) return Bot.roomReply(room, by, unxa);
id = Object.keys(Bot.rooms[room].othello).find(k => {
const game = Bot.rooms[room].othello[k];
if (cargs.includes(game.W.id) && cargs.includes(game.B.id)) return true;
});
}
if (!id) return Bot.roomReply(room, by, "Unable to find the game you're talking about. :(");
const game = Bot.rooms[room].othello[id];
if (!game) return Bot.roomReply(room, by, "Invalid ID.");
if (!game.started) Bot.say(room, `/changeuhtml OTHELLO-${id}, <hr/>Ended. :(<hr/>`);
clearGameTimer(game);
delete Bot.rooms[room].othello[id];
fs.unlink(`./data/BACKUPS/othello-${room}-${id}.json`, () => {});
return Bot.say(room, `Welp, ended Othello#${id}.`);
}
case 'endf': case 'ef': {
if (!Bot.rooms[room].othello) return Bot.roomReply(room, by, 'This room does not have any Othello games.');
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
args.shift();
const [id, winner] = args.join('').split(',').map(toID);
if (!Object.keys(Bot.rooms[room].othello).length) return Bot.roomReply(room, by, "No games are active.");
if (!id) return Bot.roomReply(room, by, "Unable to find the game you're talking about. :(");
const game = Bot.rooms[room].othello[id];
if (!game) return Bot.roomReply(room, by, "Invalid ID.");
clearGameTimer(game);
if (!game.started) {
delete Bot.rooms[room][gameName][game.id];
fs.unlink(`./data/BACKUPS/othello-${room}-${id}.json`, () => {});
return Bot.say(room, `/changeuhtml OTHELLO-${id}, <hr/>Ended. :(<hr/>`);
} else if (!winner || ![game.W.id, game.B.id, 'none'].includes(winner)) {
return Bot.roomReply(room, by, `W-who won, again?`);
}
if (toID(by) === winner) return Bot.roomReply(room, by, 'Only I may be corrupt');
runMoves(winner === 'none' ? 'forcedraw' : 'resign', game.W.id === winner ? 'B' : 'W', game);
break;
}
case 'backups': case 'bu': case 'stashed': case 'b': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, "Access denied.");
if (isPM) return Bot.roomReply(room, by, `Please use this in the room. Please. PLEASE`);
fs.readdir('./data/BACKUPS', (err, files) => {
if (err) {
Bot.say(room, err);
return Bot.log(err);
}
const games = files
.filter(file => file.startsWith(`othello-${room}-`))
.map(file => file.slice(0, -4))
.map(file => file.replace(/[^0-9]/g, ''));
if (games.length) {
Bot.say(room, `/adduhtml OTHELLOBACKUPS, <details><summary>Game Backups</summary><hr />${games.map(game => {
const info = require(`../../data/BACKUPS/othello-${room}-${game}.json`);
// eslint-disable-next-line max-len
return `<button name="send" value="/botmsg ${Bot.status.nickName},${prefix}othello ${room} restore ${game}">${info.W.name} vs ${info.B.name}</button>`;
}).join('<br />')}</details>`);
} else Bot.say(room, "No backups found.");
});
break;
}
case 'restore': case 'resume': case 'r': {
args.shift();
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, "Access denied.");
const id = parseInt(args.join(''));
if (!id) return Bot.say(room, "Invalid ID.");
if (Bot.rooms[room].othello?.[id]) return Bot.roomReply(room, by, "Sorry, that game is already in progress!");
fs.readFile(`./data/BACKUPS/othello-${room}-${id}.json`, 'utf8', (err, file) => {
if (err) return Bot.say(room, "Sorry, couldn't find that game!");
if (!Bot.rooms[room].othello) Bot.rooms[room].othello = {};
Bot.rooms[room].othello[id] = GAMES.create('othello', id, room, JSON.parse(file));
Bot.say(room, "Game has been restored!");
const game = Bot.rooms[room].othello[id];
game.spectatorSend(`<center><h1>${game[game.turn].name}'s Turn (${game.turn})</h1>${game.boardHTML()}</center>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.W.id}, Othello + ${room} + ${id}, ${game.turn === 'W' ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${game.B.id}, Othello + ${room} + ${id}, ${game.turn === 'B' ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
});
break;
}
case 'menu': case 'm': case 'list': case 'l': case 'players': {
const othello = Bot.rooms[room].othello;
if (!othello || !Object.keys(othello).length) {
if (tools.hasPermission(by, 'gamma', room) && !isPM) return Bot.say(room, "Sorry, no games found.");
return Bot.roomReply(room, by, "Sorry, no games found.");
}
const html = `<hr />${Object.keys(othello).map(id => {
const game = othello[id];
// eslint-disable-next-line max-len
return `${game.W.name ? tools.colourize(game.W.name) : `<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room} join ${id} White">White</button>`} vs ${game.B.name ? tools.colourize(game.B.name) : `<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room} join ${id} Black">Black</button>`} ${game.started ? `<button name="send" value ="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room} spectate ${id}">Watch</button> ` : ''}(#${id})`;
}).join('<br />')}<hr />`;
const staffHTML = `<hr />${Object.keys(othello).map(id => {
const game = othello[id];
// eslint-disable-next-line max-len
return `${game.W.name ? tools.colourize(game.W.name) : `<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room} join ${id} White">White</button>`} vs ${game.B.name ? tools.colourize(game.B.name) : `<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room} join ${id} Black">Black</button>`} ${game.started ? `<button name="send" value ="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room} spectate ${id}">Watch</button> ` : ''}${tools.hasPermission(by, 'gamma', room) ? `<button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room} end ${id}">End</button> <button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}othello ${room} stash ${id}">Stash</button>` : ''}(#${id})`;
}).join('<br />')}<hr />`;
if (isPM === 'export') return [html, staffHTML];
if (tools.hasPermission(by, 'gamma', room) && !isPM) {
Bot.say(room, `/adduhtml OTHELLOMENU,${html}`);
Bot.say(room, `/changerankuhtml +, OTHELLOMENU, ${staffHTML}`);
} else Bot.say(room, `/sendprivatehtmlbox ${by}, ${html}`);
break;
}
case 'resign': case 'forfeit': case 'f': case 'ff': case 'ihavebeenpwned': case 'bully': {
if (!Bot.rooms[room].othello) return Bot.roomReply(room, by, 'There isn\'t an active Othello game in this room.');
args.shift();
let id;
const user = toID(by);
if (args.length) id = toID(args.join(''));
else if (Object.keys(Bot.rooms[room].othello).length === 1) id = Object.keys(Bot.rooms[room].othello)[0];
else id = Object.keys(Bot.rooms[room].othello).find(k => {
const game = Bot.rooms[room].othello[k];
return game && game.started && [game.W.id, game.B.id].includes(user);
});
if (!id) return Bot.roomReply(room, by, "Unable to find the game you meant to play in.");
const game = Bot.rooms[room].othello[id];
if (!game) return Bot.roomReply(room, by, "Not a valid ID.");
if (!game.started) return Bot.roomReply(room, by, '>resigning before it starts');
if (![game.W.id, game.B.id].includes(user)) return Bot.roomReply(room, by, "Only a id can resign.");
const side = game.W.id === user ? 'W' : 'B';
if (!game[side].isResigning) {
Bot.roomReply(room, by, 'Are you sure you want to resign? If you are, use this command again.');
return game[side].isResigning = true;
}
clearGameTimer(game);
runMoves('resign', side, game);
break;
}
case 'spectate': case 's': case 'watch': case 'w': {
if (!Bot.rooms[room].othello) return Bot.roomReply(room, by, 'This room does not have any Othello games.');
args.shift();
let id;
if (args.length && /^[^a-zA-Z]+$/.test(args.join(''))) id = toID(args.join(''));
else if (Object.keys(Bot.rooms[room].othello).length === 1) id = Object.keys(Bot.rooms[room].othello)[0];
else if (Object.values(Bot.rooms[room].othello).filter(game => game.started).length === 1) {
id = Object.values(Bot.rooms[room].othello).filter(game => game.started)[0].id;
} else {
const cargs = args.join('').split(/(?:,|\s+v(?:er)?s(?:us)?\.?\s+)/).map(toID);
if (cargs.length !== 2) return Bot.roomReply(room, by, "Sorry, specify the players again?");
id = Object.keys(Bot.rooms[room].othello).find(k => {
const game = Bot.rooms[room].othello[k];
if (cargs.includes(game.W.id) && cargs.includes(game.B.id) && !game.spectators.includes(toID(by))) {
return true;
}
});
}
const game = Bot.rooms[room].othello[id];
if (!game) return Bot.roomReply(room, by, "Sorry, no Othello game here to spectate.");
if (!game.started) Bot.roomReply(room, by, "Oki, I'll send you the board when it starts.");
const user = toID(by);
if ([game.W.id, game.B.id].includes(user)) return Bot.roomReply(room, by, "Imagine spectating your own game.");
if (!game.spectators.includes(user)) game.spectators.push(user);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${by}, Othello + ${room} + ${id}, <center><h1>${game[game.turn].name}'s Turn (${game.turn})</h1>${game.boardHTML()}</center>`);
Bot.roomReply(room, by, `You are now spectating the Othello match between ${game.W.name} and ${game.B.name}!`);
break;
}
case 'unspectate': case 'us': case 'unwatch': case 'uw': case 'zestoflifeisstinky': {
if (!Bot.rooms[room].othello) return Bot.roomReply(room, by, 'This room does not have any Othello games.');
args.shift();
let id;
if (args.length && /^[^a-zA-Z]+$/.test(args.join(''))) id = toID(args.join(''));
else if (Object.values(Bot.rooms[room].othello).filter(game => game.spectators.includes(toID(by))).length === 1) {
id = Object.values(Bot.rooms[room].othello).filter(game => game.spectators.includes(toID(by)))[0].id;
} else {
const cargs = args.join('').split(/(?:,|\s+v(?:er)?s(?:us)?\.?\s+)/).map(toID);
if (cargs.length !== 2) return Bot.roomReply(room, by, "Sorry, didn't get the game you meant.");
id = Object.keys(Bot.rooms[room].othello).find(k => {
const game = Bot.rooms[room].othello[k];
if (cargs.includes(game.W.id) && cargs.includes(game.B.id) && game.spectators.includes(toID(by))) {
return true;
}
});
}
const game = Bot.rooms[room].othello[id];
if (!game) return Bot.roomReply(room, by, "Sorry, no Othello game here to unspectate.");
if (!game.started) return Bot.roomReply(room, by, "AYAYAYA - no.");
const user = toID(by);
if ([game.W.id, game.B.id].includes(user)) return Bot.roomReply(room, by, "Imagine unspectating your own game.");
if (!game.spectators.includes(user)) {
// eslint-disable-next-line max-len
return Bot.roomReply(room, by, `You aren't spectating! If you want to, use \`\`${prefix}othello spectate\`\` instead!`);
}
game.spectators.remove(user);
Bot.roomReply(room, by, `You are no longer spectating the Othello match between ${game.W.name} and ${game.B.name}.`);
break;
}
case 'rejoin': case 'rj': {
const games = Bot.rooms[room].othello;
if (!games) return Bot.roomReply(room, by, "Sorry, no Othello game here to spectate.");
const user = toID(by);
const ids = Object.keys(games)
.filter(key => [games[key].W.id, games[key].B.id, ...games[key].spectators].includes(user));
if (!ids.length) return Bot.roomReply(room, by, "Couldn't find any games for you to rejoin.");
ids.forEach(id => {
const game = games[id];
let side;
if (game.W.id === user) side = 'W';
if (game.B.id === user) side = 'B';
if (!game.started) return;
if (!side && !game.spectators.includes(toID(by))) {
// eslint-disable-next-line max-len
return Bot.roomReply(room, by, `You don't look like a id / spectator - try ${prefix}othello spectate ${id}... ;-;`);
}
if (game.spectators.includes(user)) {
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${by}, Othello + ${room} + ${id}, <center><h1>${game[game.turn].name}'s Turn (${game.turn})</h1>${game.boardHTML()}</center>`);
} else {
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${user}, Othello + ${room} + ${id}, ${game.turn === side ? "<h1 style=\"text-align: center;\">Your turn!</h1>" : "<h1 style=\"text-align: center;\">Waiting for opponent...</h1>"}<center>${game.boardHTML(true)}</center>`);
}
});
break;
}
case 'stash': case 'store': case 'freeze': case 'hold': case 'h': {
if (!tools.hasPermission(by, 'gamma', room)) return Bot.roomReply(room, by, 'Access denied.');
if (!Bot.rooms[room].othello) return Bot.roomReply(room, by, 'This room does not have any Othello games.');
args.shift();
let id;
if (!Object.keys(Bot.rooms[room].othello).length) return Bot.roomReply(room, by, "No games are active.");
if (args.length && /^[^a-zA-Z]+$/.test(args.join(''))) id = toID(args.join(''));
else if (Object.keys(Bot.rooms[room].othello).length === 1) id = Object.keys(Bot.rooms[room].othello)[0];
else {
const cargs = args.join('').split(/(?:,|\s+v(?:er)?s(?:us)?\.?\s+)/).map(toID);
if (cargs.length !== 2) return Bot.roomReply(room, by, unxa);
id = Object.keys(Bot.rooms[room].othello).find(k => {
const game = Bot.rooms[room].othello[k];
if (cargs.includes(game.W.id) && cargs.includes(game.B.id)) return true;
});
}
if (!id) return Bot.roomReply(room, by, "Unable to find the game you're talking about. :(");
const game = Bot.rooms[room].othello[id];
if (!game) return Bot.roomReply(room, by, "Invalid ID.");
Bot.say(room, `The Othello match between ${game.W.name} and ${game.B.name} has been put on hold!`);
delete Bot.rooms[room].othello[id];
break;
}
default: {
Bot.roomReply(room, by, `That, uhh, doesn't seem to be something I recognize?`);
break;
}
}
}
};
<file_sep>/commands/global/atm.js
module.exports = {
cooldown: 100,
help: `Displays a user's points in the room.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
let out;
const user = args[0] ? toID(args.join('')) : toID(by);
if (!Bot.rooms[room].lb) out = 'This room doesn\'t have a Leaderboard.';
else if (Bot.rooms[room].lb.users[user]) {
if (Bot.rooms[room].lb.users[user].points.reduce((a, b) => a || b, false)) {
const points = Bot.rooms[room].lb.users[user].points.filter((p, i) => p > 0 && Bot.rooms[room].lb.points[i]);
const pointsStr = points.map((p, i) => p + ' ' + Bot.rooms[room].lb.points[i][2]).join(', ');
out = ` ${Bot.rooms[room].lb.users[user].name}'s points: ${pointsStr}.`;
} else out = 'This user doesn\'t have any points in this room!';
} else out = 'This user doesn\'t have any points in this room!';
if (tools.hasPermission(by, 'gamma', room)) return Bot.say(room, out);
else return Bot.pm(by, out);
}
};
<file_sep>/discord/bonk.js
module.exports = {
help: `BONK`,
guildOnly: ["226909807548825600", "776284091813068830"],
commandFunction: function (args, message, Bot) {
message.channel.send("https://emoji.gg/assets/emoji/9749_bonk.png");
}
};
<file_sep>/commands/global/whitelist.js
// TODO: Use a database instead
module.exports = {
help: `Whitelist! Syntax: ${prefix}whitelist add/remove/list`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
const auth = Bot.rooms[room].auth?.gamma;
if (!auth) return Bot.say(room, `The whitelist has not been enabled for this room - please contact my owner.`);
if (!args.length) args.push('list');
function updateRoom (gamma) {
const roomFile = fs.readFileSync(`./data/ROOMS/${room}.json`, 'utf8');
if (!roomFile) return Bot.log(`Error: Could not find file for room ${room}`);
const newJSON = roomFile.replace(/(?<=\n\t\t"gamma": \[).*?(?=\]\n)/, gamma.map(u => `"${u}"`).join(', '));
fs.writeFileSync(`./data/ROOMS/${room}.json`, newJSON);
Bot.log(`Updated JSON for ${room}`);
(async () => {
try {
const output = require('child_process')
.execSync('git add data/ROOMS && git commit -m "Update rooms" && git push origin main')
.toString();
Bot.log(output);
} catch (e) {
Bot.log(e);
}
})();
}
switch (toID(args.shift())) {
case 'add': case 'a': {
const u = toID(args.join(''));
if (!u || u.length > 19 || auth.includes(u)) return Bot.say(room, `Invalid user to add to whitelist (${u})`);
auth.push(u);
auth.sort();
updateRoom(auth);
return Bot.say(room, `${u} was added to the whitelist!`);
}
case 'remove': case 'delete': case 'r': case 'd': case 'x': {
const u = toID(args.join(''));
if (!u || u.length > 19 || !auth.includes(u)) return Bot.say(room, `Invalid user to remove from whitelist (${u})`);
auth.remove(u);
updateRoom(auth);
return Bot.say(room, `${u} was removed from the whitelist.`);
}
case 'list': case 'l': case 'all': case 'view': case 'v': {
const whitelistHtml = tools.listify(auth.map(u => tools.colourize(u)));
return Bot.say(room, `/adduhtml BOTWHITELIST, The current whitelist is: ${whitelistHtml}`);
}
default: return Bot.say(room, 'Unrecognized option');
}
}
};
<file_sep>/pmcommands/pogoregister.js
module.exports = {
noDisplay: true,
help: `Registers you on PoGo`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
const room = 'pokemongo';
if (!Bot.rooms[room]?.users.some(u => toID(u) === toID(by))) return Bot.pm(by, '<<pokemongo>>');
return Bot.commandHandler('setuser', by, args, room, by);
}
};
<file_sep>/pmcommands/hotpatch.js
module.exports = {
cooldown: 1,
help: `Hotpatches stuff.`,
permissions: 'coder',
commandFunction: function (Bot, by, args, client) {
if (!args[0]) return Bot.pm(by, unxa);
Bot.hotpatch(args.join(' '), by)
.then(out => Bot.pm(by, `Successfully hotpatched: ${out}.`)).catch(e => Bot.pm(by, `Hotpatch failed: ${e}`));
}
};
<file_sep>/commands/global/link.js
module.exports = {
cooldown: 100,
help: `Links an image in a room.`,
permissions: 'gamma',
commandFunction: function (Bot, room, time, by, args, client) {
return Bot.pm(by, 'Sorry, work in progress.');
// Made irrelevant by !show
if (!args[0]) return Bot.say(room, unxa);
let line = args.join(' ');
if (!/^https?:\/\//.test(line)) line = 'http://' + line;
line = line.split('//');
const link = line.splice(0, 2).join('//'), text = line.join('//');
axios.get(link).then(body => {
if (error) return Bot.say(room, 'Invalid link.');
if (/\.(?:png|jpg|gif)$/.test(link)) {
// eslint-disable-next-line max-len
return Bot.say(room, `/adduhtml LINK, <img src="${link}" width="0" height="0" style="width:auto;height:auto"><br/>${text}`);
}
const image = body.match(/<img .*?>/i);
if (!image) return Bot.say(room, "The given link doesn't have an image!");
// eslint-disable-next-line max-len
return Bot.say(room, `/adduhtml LINK, ${image[0].substr(0, image[0].length - 1)} width="0" height="0" style="width:auto;height:auto"><br/>${text}`);
});
}
};
<file_sep>/handlers/watcher.js
module.exports = function watcher () {
const watchers = [];
const watchHots = [{
path: './data/ALIASES',
name: 'aliases'
}, {
path: './handlers/autores.js',
name: 'autores'
}, {
path: './handlers/chat.js',
name: 'chat'
}, {
path: './handlers/discord_chat.js',
name: 'discord'
}, {
path: './handlers/events.js',
name: 'events'
}, {
path: './data/GAMES',
name: 'games'
}, {
path: './global.js',
name: 'global'
}, {
path: './data/hotpatch.js',
name: 'hotpatch'
}, {
path: './handlers/minorhandler.js',
name: 'minor'
}, {
path: './handlers/pages.js',
name: 'pages'
}, {
path: './handlers/pmhandler.js',
name: 'pms'
}, {
path: './data/ROOMS',
name: 'rooms'
}, {
path: './handlers/router.js',
name: 'router'
}, {
path: './handlers/schedule.js',
name: 'schedule'
}, {
path: './handlers/ticker.js',
name: 'ticker'
}, {
path: './data/tools.js',
name: 'tools'
}, {
path: './handlers/tours.js',
name: 'tour'
}, {
path: './handlers/watcher.js',
name: 'watcher'
}];
watchHots.forEach(watch => watchers.push(fs.watch(watch.path, (event, name) => {
if (event === 'change') Bot.hotpatch(watch.name, '*Sentinel')
.then(res => client.channels.cache.get('848835497845194752').send(`Hotpatched: ${res}`))
.catch(err => client.channels.cache.get('848835497845194752').send(`Unable to hotpatch ${watch.name} because: ${err}`));
})));
fs.readdirSync('./commands').forEach(folder => {
watchers.push(fs.watch(`./commands/${folder}`, (event, name) => {
if (event === 'change') delete require.cache[require.resolve(`../commands/${folder}/${name}`)];
}));
});
watchers.push(fs.watch('./commands', (eventName, folder) => {
if (eventName === 'rename') watchers.push(fs.watch(`./commands/${folder}`, (event, name) => {
if (event === 'change') delete require.cache[require.resolve(`../commands/${folder}/${name}`)];
}));
}));
watchers.push(fs.watch('./pmcommands', (event, name) => {
if (event === 'change') delete require.cache[require.resolve(`../pmcommands/${name}`)];
}));
watchers.push(fs.watch('./discord', (event, name) => {
if (event === 'change') delete require.cache[require.resolve(`../discord/${name}`)];
}));
['bot.js', 'client.js'].forEach(file => watchers.push(fs.watch(file, (event, name) => {
if (event === 'change') {
const logChannel = client.channels.cache.get('848835497845194752');
logChannel.send(`<@!333219724890603520> Changes have been pushed that require a restart`);
}
})));
return {
watchers: watchers,
close: () => watchers.forEach(swatch => swatch.close())
};
// This is untouched, but I'd highly recommend switching out some of the code here and
// setting up a small system to detect Git webhooks and automatically hotpatch.
};
<file_sep>/discord/test.js
module.exports = {
help: `Test`,
admin: true,
guildOnly: '719076445699440700',
commandFunction: function (args, message, Bot) {
message.channel.send('o/');
}
};
<file_sep>/handlers/pmhandler.js
module.exports = function handler (by, message) {
if (message.startsWith('/invite')) {
for (const room of config.autoJoin) if (message.startsWith(`/invite ${room}`)) return Bot.joinRooms([room]);
if (['+', '%', '@', '&', '~'].includes(by.charAt(0)) || tools.hasPermission(by, 'beta')) {
return Bot.joinRooms([message.split('/invite')[1]]);
}
if (message.startsWith('/invite battle-')) return Bot.joinRooms([message.split('/invite ')[1]]);
if (tools.hasPermission(by, 'beta', 'hindi')) return Bot.joinRooms([message.split('/invite ')[1]]);
if (['crowmusic', 'premmalhotra', 'rajshoot', 'shivamo', 'thedarkrising'].includes(toID(by))) {
return Bot.joinRooms([message.split('/invite ')[1]]);
}
return Bot.pm(by, "Sorry, only global staff can invite me.");
}
if (message.startsWith('|requestpage|')) {
const [__, reqp, user, title] = message.split('|');
if (!title) return;
return Bot.pageHandler(by, title);
}
if (message.startsWith('/challenge ')) {
const validTiers = Bot.teams;
const [tier] = message.substr('/challenge '.length).split('|');
if (tier === 'constructor') return Bot.pm(by, 'Okay this is getting out of hand now');
if (!validTiers[tier]) {
Bot.pm(by, `Sorry, I don't play that! Valid tiers are: ${Object.values(validTiers).map(t => t.name).join(', ')}`);
return Bot.say('', `/reject ${by}`);
}
const team = validTiers[tier].teams?.random();
if (team) Bot.say('', `/utm ${team}`);
Bot.say('', `/accept ${by}`);
Bot.log(`Fighting ${by}`);
}
if (message.toLowerCase().includes('mental math')) {
if (Bot.rooms[mmroom]) return Bot.say(mmroom, '/invite ' + by);
else return Bot.pm(by, 'Sorry, but the groupchat is down.');
}
if (message.startsWith('/botmsg ')) message = message.substr(8);
if (!message.startsWith(prefix)) {
if (config.debug) {
// eslint-disable-next-line max-len
client.channels.cache.get('826473646944026644').send(`${by}: ${message.substr(0, 1950) + (message.length > 1950 ? '...' : '')}`.replace(/@(?:everyone|here)/g, m => `@\u200b${m.substr(1)}`));
}
if (message.toLowerCase().includes('invite')) {
if (!Bot.rooms[tcroom]) return Bot.pm(by, 'Not currently up, sorry.');
return Bot.say(tcroom, '/invite ' + by);
}
if (/krytoconiscute/.test(toID(message))) {
if (!Bot.rooms['groupchat-partbot-1v1mnm']) return Bot.pm(by, 'Nah, you missed it.');
return Bot.say('groupchat-partbot-1v1mnm', '/invite ' + by);
}
if (!Bot.auth.admin.includes(toID(by))) {
if (Bot.lastPMHelp === toID(by)) return;
Bot.lastPMHelp = toID(by);
// eslint-disable-next-line max-len
return Bot.pm(by, `Hi, I'm ${Bot.status.nickName}! I'm a Bot. My prefix is \`\`${prefix}\`\`. For an overview of my commands, use \`\`${prefix}commands\`\`.`);
}
return;
}
const args = message.substr(prefix.length).split(' ');
const commandName = tools.pmCommandAlias(args.shift());
if (!commandName) return;
if (['eval', 'output'].includes(commandName)) {
if (!tools.hasPermission(toID(by), 'admin')) return Bot.pm(by, 'Access denied.');
try {
let outp = eval(args.join(' '));
switch (typeof outp) {
case 'object': outp = JSON.stringify(outp, null, 2); break;
case 'function': outp = outp.toString(); break;
case 'undefined': outp = 'undefined'; break;
}
Bot.pm(by, '!code ' + String(outp));
} catch (e) {
console.log(e); Bot.pm(by, e.message); Bot.log(e);
}
return;
}
fs.readdir('./pmcommands', (err, files) => {
if (err) {
Bot.auth.admin.forEach(adm => Bot.pm(adm, err.message)); Bot.log(err);
}
const commands = files.map(file => file.slice(0, file.length - 3));
if (!commands.includes(commandName)) return Bot.pm(by, `It doesn't look like that command exists.`);
const commandRequire = require(`../pmcommands/${commandName}.js`);
if (!tools.hasPermission(by, commandRequire.permissions)) {
return Bot.pm(by, 'Access denied.');
}
try {
commandRequire.commandFunction(Bot, by, args, client);
} catch (e) {
if (e) {
Bot.pm(by, e.message); return Bot.log(e);
}
}
});
return;
};
<file_sep>/commands/global/help.js
module.exports = {
cooldown: 1000,
help: `Displays the help for a command. Syntax: ${prefix}help (command)`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args[0]) {
// eslint-disable-next-line max-len
return Bot.pm(by, 'I\'m a Bot by PartMan. If you have any issues regarding me, please contact them. To see my usable commands, use the ``' + prefix + 'commands`` command.');
}
const commandName = tools.commandAlias(toID(args.join('')));
fs.readdir('./commands/global', (e, gcommands) => {
if (e) return console.log(e);
if (gcommands.includes(commandName + '.js')) {
const commandReq = require('./' + commandName + '.js');
if (!tools.hasPermission(by, commandReq.permissions, room)) return Bot.pm(by, 'Shh.');
Bot.say(room, commandReq.help);
} else {
fs.readdir('./commands/' + room, (e, files) => {
if (e || !files.includes(commandName + '.js')) return Bot.pm(by, 'It doesn\'t look like that command exists.');
const commandReq = require('../' + room + '/' + commandName + '.js');
if (!tools.hasPermission(by, commandReq.permissions, room)) return Bot.say(room, 'Shh.');
Bot.say(room, commandReq.help);
});
}
});
}
};
<file_sep>/commands/global/website.js
module.exports = {
cooldown: 1,
help: `Displays the website link.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `/pm ${by}, ${websiteLink}`);
}
};
<file_sep>/discord/usehint.js
const PZ = require('../data/PUZZLES/index.js');
module.exports = {
help: `Uses a hint for a puzzle.`,
guildOnly: PZ.guildID,
commandFunction: function (args, message, Bot) {
if (!PZ.live) return message.channel.send("Sorry, this command may not be used at this time. 'o.o");
const team = PZ.getTeam(message.member);
if (!team) return message.channel.send("You don't seem to be participating... maybe contact one of our staff?");
if (team.channel !== message.channel.id) {
return message.channel.send("Please only use this in your own team's channel.").then(msg => {
msg.delete({ timeout: 3000 });
message.delete({ timeout: 3000 });
});
}
if (!args.length) return message.channel.send("Which puzzle?");
const puzzle = PZ.getPuzzle(toID(args.join('')));
if (!puzzle || !team.unlocked.includes(puzzle.index)) return message.channel.send("Puzzle not found.");
if (!team.hints) return message.channel.send("Sorry, but it doesn't look like you have any available hints!");
if (team.puzzles[puzzle.index]) return message.channel.send(`Here's a hint - you've solved it!`);
message.channel.send('Hint request has been commenced. Please type \'confirm\' within the next minute to confirm.');
message.channel.awaitMessages(msg => {
return /confirm/i.test(msg.content) && msg.author.id === message.author.id;
}, { max: 1, time: 60000, errors: ['time'] }).then(col => {
message.channel.send('Noted; a staff member will be here as soon as they can.');
// eslint-disable-next-line max-len
PZ.hintChannel.send(`<@&${PZ.IDs.staff}>: A hint has been requested in <#${team.channel}>.\n\nRemember to react with :thumbsup: if you're handling it.`);
PZ.addHints(team, -1, false);
}).catch(e => {
// eslint-disable-next-line max-len
message.channel.send("The hint usage has not been confirmed in time, and has been cancelled. A hint will not be consumed.");
});
}
};
<file_sep>/pmcommands/q.js
module.exports = {
help: `Quotes! Use \`\`${prefix}q room | command\`\`. For a list of subcommands, use \`\`${prefix}q help\`\``,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
if (['m', 'room'].includes((args[0] || '').toLowerCase())) args.shift();
let [room, ctx] = args.join(' ').splitFirst('|').map(t => t.trim());
room = tools.getRoom(room);
if (['h', 'help'].includes(room)) [room, ctx] = ['botdevelopment', 'help'];
if (!room) {
let rooms = Bot.getRooms(by);
if (!rooms) rooms = [];
rooms = rooms.filter(r => Bot.rooms[r]);
if (rooms.length === 0) return Bot.pm(by, "You don't know any of my rooms...");
if (rooms.length === 1) room = rooms[0];
// eslint-disable-next-line max-len
else return Bot.sendHTML(by, `We share multiple rooms! Which did you mean?<br>` + rooms.map(r => `<button name="send" value="/msg ${Bot.status.nickName},${prefix}q ${Bot.rooms[r]?.title || r} | random">${Bot.rooms[r].title}</button>`));
}
if (!room || !Bot.rooms[room]) {
// eslint-disable-next-line max-len
return Bot.pm(by, `Invalid room. The syntax for this was recently changed; consult \`\`${prefix}help q\`\` for more details.`);
}
return Bot.commandHandler('q', by, ctx?.split(' ') || [], room, true);
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/experts.js
module.exports = {
cooldown: 1000,
help: `Displays the experts for a given area. Syntax: ${prefix}experts (type / all)`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
return Bot.pm(by, 'This command is under a constrictor! To avoid being swallowed by a snake, please append a ``7`` to the command and try again.');
if (!args[0] || args[2]) return Bot.say(room, unxa);
if (!typelist.includes(args[0].toLowerCase()) && !args[0].toLowerCase() === 'all') return Bot.say(room, 'That type doesn\'t seem to exist.');
if (args[0].toLowerCase() === 'all') {
const outarr = [];
typelist.forEach(function (type) {
const edoc = require('../../data/EXPERTS/tc.js')[type];
if (edoc == undefined) return Bot.say(room, 'Something went wrong. Blame PartMan.');
let outputv = '';
if (edoc.length === 0) outputv = `There are no TC ${tools.toName(type)} Experts.`;
else {
const temparr = edoc.sort().map(exps => tools.colourize(tools.toName(exps)));
outputv = `The TC ${tools.toName(type)} Expert${edoc.length === 1 ? ' is' : 's are'} ${tools.listify(temparr)}.`;
}
outarr.push(outputv);
});
if (tools.hasPermission(by, 'gamma')) return Bot.say(room, '/adduhtml EXPERTS, <HR>' + outarr.join('<BR>') + '<HR>');
else return Bot.say(room, '/pminfobox ' + by + ', ' + outarr.join('<BR>'));
}
if (!typelist.includes(args[0].toLowerCase())) return Bot.say(room, 'It doesn\'t look like that type exists.');
const edoc = require('../../data/EXPERTS/tc.js')[args[0].toLowerCase()];
if (edoc == undefined) return Bot.say(room, 'Something went wrong. Blame PartMan.');
let temparr = [];
let outputv = '';
if (edoc.length === 0) outputv = `There are no TC ${tools.toName(args[0].toLowerCase())} Experts.`;
else if (edoc.length === 1) outputv = `The TC ${tools.toName(args[0].toLowerCase())} Expert is ${tools.colourize(tools.toName(edoc[0]), edoc[0])}.`;
else {
temparr = edoc.sort().map(exps => tools.colourize(tools.toName(exps)));
outputv = `The TC ${tools.toName(args[0].toLowerCase())} Experts ${temparr[1] ? 'are' : 'is'} ${tools.listify(temparr)}.`;
}
if (tools.hasPermission(by, 'gamma', room)) return Bot.say(room, '/adduhtml EXPERTS, <HR>' + outputv + '<HR>');
else return Bot.say(room, '/pminfobox ' + by + ', ' + outputv);
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/rt.js
module.exports = {
cooldown: 1000,
help: `Displays a random type.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
const rtype = typelist[Math.floor(18 * Math.random())];
if (tools.hasPermission(by, 'gamma', room)) Bot.say(room, `/adduhtml TYPE,Random Type: ${tools.colourize(tools.toName(rtype))}`);
else Bot.say(room, '/pminfobox ' + by + ', ' + `Random Type: ${tools.colourize(tools.toName(rtype))}`);
}
};
<file_sep>/commands/petsanimals/setpet.js
module.exports = {
cooldown: 0,
// eslint-disable-next-line max-len
help: `Configures info about your pet(s). Syntax: ${prefix}setpet (entry1): (value1), (entry2): (value2)... [entries can be name/species]`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client, isFrom) {
const DB = Bot.DB('pets');
const username = toID(by), displayName = by.substr(1);
const user = DB.get(username) || { pets: {} };
if (username === 'constructor') return Bot.pm(isFrom, `...can you not, please?`);
user.name = displayName;
let pet = {};
const validEntries = ['name', 'type', 'species'];
const entries = args
.join(' ')
.replace(/[^a-zA-Z0-9,: ]/g, '')
.split(',')
.filter(k => k.indexOf(':') >= 0)
.map(k => k.split(':', 2))
.filter(k => k[1])
.map(k => [k[0].toLowerCase().trim(), k[1].trim()]);
for (const entry of entries) {
if (!validEntries.includes(entry[0])) {
return Bot.roomReply(room, by, `Sorry, that wasn't a valid entry! Valid entries are: ${validEntries.join(', ')}`);
}
pet[entry[0]] = entry[1];
}
if (!pet.name) return Bot.roomReply(room, by, `Which pet are you speaking of?`);
if (user.pets[toID(pet.name)]) {
const temp = user.pets[toID(pet.name)];
Object.entries(pet).forEach(([k, v]) => temp[k] = v);
pet = temp;
}
if (!pet.images) pet.images = [];
const petTypes = ['bird', 'cat', 'dog', 'fish', 'reptile', 'rodent', 'other'];
if (pet.type && !petTypes.includes(pet.type)) {
return Bot.roomReply(room, by, `The only valid types of pets are: ${tools.listify(petTypes)}`);
}
if (toID(pet.name) === 'constructor') return Bot.roomReply(room, by, `That is a VERY suspicious snek`);
if (toID(pet.name) === 'hydro') {
return Bot.roomReply(room, by, `We all dream of having Hydro as a pet. Who are you, to have done the impossible?`);
}
if (toID(pet.name) === 'partbot') return Bot.roomReply(room, by, `I AM NOT YOUR PET! >:I`);
user.pets[toID(pet.name)] = pet;
Bot.say(room, `!code ${JSON.stringify(user)}`);
DB.set(username, user);
Bot.say(room, `/sendprivatehtmlbox ${isFrom || by}, Your pet has been added/updated (too lazy to check again)`);
}
};
<file_sep>/commands/pokemongo/wishlist.js
module.exports = {
help: `Shows a list of people who're looking for a specific Pokemon`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client, isPM) {
function reject (m) {
if (tools.hasPermission(by, room, 'gamma') && !isPM) return Bot.say(room, m);
else return isPM ? Bot.pm(by, m) : Bot.roomReply(room, by, m);
}
const protoDB = require('origindb')('data/POGO'), DB = protoDB('users');
const monID = toID(args.join(''));
if (!monID) return reject(`Please mention the Pokemon's name!`);
if (monID === 'constructor') {
return reject(`Error: cannot read property 'constructor' of a random nerd who's trying to break me`);
}
const mon = data.pokedex[monID];
if (!mon) {
// eslint-disable-next-line max-len
return reject(`Sorry, but I don't recognize ${monID} as a Pokemon! Please format the name the same way Pokemon Showdown does!`);
}
const users = Object.values(DB.object()).filter(user => user.raids.hasOwnProperty(monID));
const format = user => {
let out = `${user.displayName} [${user.ign}]`;
if (Bot.rooms[room].users.find(u => toID(u) === user.username)) out = `<strong>${out}</strong>`;
return out;
};
const nwb = users.filter(user => user.raids[monID] === false);
const wb = users.filter(user => user.raids[monID] === true);
// eslint-disable-next-line max-len
const html = `<div style="font-size:1.2em;font-weight:bold;margin-top:5px;">Looking for ${mon.name} (${nwb.length}+${wb.length})</div><br/>${nwb.map(format).join('<br/>')}${wb.length ? `<br/><details style="margin-top:5px;"><summary>(only Weather Boosted)</summary>${wb.map(format).join('<br/>')}</details>` : ''}`;
if (isPM) Bot.sendHTML(by, html);
else if (tools.hasPermission(by, 'gamma', room)) Bot.say(room, `/adduhtml WISHLIST${monID}, ${html}`);
else Bot.say(room, `/sendprivateuhtml WISHLIST${monID}, ${html}`);
}
};
<file_sep>/commands/pokemongo/showmycode.js
module.exports = {
cooldown: 500,
help: `Broadcasts your Pokemon Go Friend Code.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
const protoDB = require('origindb')('data/POGO'), DB = protoDB('users');
const user = DB.get(toID(by));
if (!user) return Bot.roomReply(room, by, `You're not registered - try registering using ${prefix}setuser!`);
Bot.say(room, `${by.substr(1)} is registered as the Lv${user.level} ${user.ign} - their Friend Code is ${user.code}.`);
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/tc7.js
module.exports = {
cooldown: 10000,
help: `Starts a Tournament with the given options. Syntax: ${prefix}tc (random/type) (e[n]/rr/drr) (official)`,
permissions: 'beta',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args[0]) return Bot.say(room, unxa);
let type = toID(args.shift());
if (type === 'random' || type === 'r') type = typelist[Math.floor(Math.random() * 18)];
if (!typelist.includes(type)) return Bot.say(room, 'Invalid Type.');
if (args[0]) args[0] = toID(args[0]);
let tourStr;
switch (args[0]) {
case undefined: case 'drr':
if (args[0]) args.shift();
tourStr = '/tour create Gen7-1v1, rr, , 2';
break;
case 'rr':
args.shift();
tourStr = '/tour create Gen7-1v1, rr';
break;
case 'o': case 'official': case 'fish': case 'fishy':
tourStr = '/tour create Gen7-1v1, rr, , 1';
break;
default:
const ttype = args.shift();
if (ttype.startsWith('e')) {
switch (parseInt(ttype.substr(1))) {
case NaN: case 1:
tourStr = '/tour create Gen7-1v1, elim';
break;
default:
tourStr = '/tour create Gen7-1v1, elim, , ' + parseInt(ttype.substr(1));
break;
}
} else return Bot.say(room, 'Invalid Tour Type.');
break;
}
const staggerSay = function (stuff) {
Bot.say(room, stuff);
};
if (args[0] && ['o', 'official', 'fish', 'fishy'].includes(toID(args[0]))) {
tourStr = '/tour create Gen7-1v1, rr';
Bot.say(room, tourStr);
Bot.say(room, '$settype ' + type);
setTimeout(staggerSay, 1000, '$official');
const tourArr = JSON.parse(fs.readFileSync('./data/DATA/tourrecords.json', 'utf8'));
tourArr.push({ official: true, type: type, starter: toID(by), time: Date.now(), gen: 7 });
fs.writeFileSync('./data/DATA/tourrecords.json', JSON.stringify(tourArr));
const reqTour = require('../../data/TOURS/CODES/TC7/' + type + '.js');
if (!reqTour[type]) return Bot.say(room, 'PartMan messed something up.');
Bot.say(room, reqTour[type]);
return client.channels.cache.get('549432010322477056').send('<@&616345204533755920> Gen7 Type: ' + type.charAt(0).toUpperCase() + type.substr(1) + ' Tour started!');
}
const reqTour = require('../../data/TOURS/CODES/TC7/' + type + '.js');
if (!reqTour[type]) return Bot.say(room, 'PartMan messed something up.');
// client.channels.cache.get('549432010322477056').send('Gen7 Type: ' + type.charAt(0).toUpperCase() + type.substr(1) + ' Tour started!');
const tourArr = JSON.parse(fs.readFileSync('./data/DATA/tourrecords.json', 'utf8'));
tourArr.push({ official: false, type: type, starter: toID(by), time: Date.now(), gen: 7 });
fs.writeFileSync('./data/DATA/tourrecords.json', JSON.stringify(tourArr));
Bot.say(room, tourStr);
Bot.say(room, '$settype ' + type);
Bot.say(room, reqTour[type]);
}
};
<file_sep>/commands/global/lightsout.js
module.exports = {
help: `The Lights Out game! Use \`\`${prefix}lightsout new\`\` to create a game, and just click from there.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client, isPM) {
if (!tools.canHTML(room)) return Bot.roomReply(room, by, "Sorry, but I kinda need to be a Bot here to do that. Try getting an RO to promote me.");
if (!Bot.rooms[room].lightsout) Bot.rooms[room].lightsout = {};
const LO = Bot.rooms[room].lightsout;
let user = toID(by);
if (!args.length) args.push('help');
switch (toID(args.shift())) {
case 'help': case 'h': case 'htp': {
if (tools.hasPermission(by, 'gamma', room) && !isPM) return Bot.say(room, "https://www.logicgamesonline.com/lightsout/");
else return Bot.roomReply(room, by, "https://www.logicgamesonline.com/lightsout/");
break;
}
case 'new': case 'n': {
if (isPM) return Bot.roomReply(room, by, `Do it in chat you nerd`);
if (LO[user]) return Bot.roomReply(room, by, `Err, you already have a game running. If you want to make a new one, try using \`\`${prefix}lightsout resign\`\` and trying again.`);
args = args.join(' ').split(/[, x]/).filter(m => m).map(n => parseInt(n));
let size;
if (args.length !== 2 || isNaN(args[0]) || isNaN(args[1])) size = [5, 5];
else size = args;
if (size[0] >= 21 || size[1] >= 21) return Bot.roomReply(room, by, "WAY TOO LARGE AAAA");
if (size[0] < 2 || size[1] < 2) return Bot.roomReply(room, by, "Sorry, I can't allow anything smaller than my IQ.");
LO[user] = GAMES.create('lightsout', room, by.substr(1), size);
const header = `<div style="display: inline-block; float: left; font-weight: bold;">My Solution: ${LO[user].soln.length} moves</div><div style="display: inline-block; float: right; font-weight: bold;">Moves Made: ${LO[user].moves.length} moves</div><br /><br /><br />`;
Bot.say(room, `/sendhtmlpage ${by}, Lights Out (${by.substr(1)}), ${header + LO[user].boardHTML(true)}`);
Bot.say(room, `${by.substr(1)} is playing a game of Lights Out - type \`\`${prefix}lightsout spectate ${by.substr(1)}\`\` to watch!`);
return;
break;
}
case 'click': case 'c': {
if (!LO[user]) return Bot.roomReply(room, by, "Err, you don't have any running games - try making one?");
args = args.map(t => parseInt(t));
const out = LO[user].click(...args);
const header = `<div style="display: inline-block; float: left; font-weight: bold;">My Solution: ${LO[user].soln.length} moves</div><div style="display: inline-block; float: right; font-weight: bold;">Moves Made: ${LO[user].moves.length} moves</div><br /><br /><br />`;
if (out === null) return Bot.roomReply(room, by, "Use the buttons. O-onegai.");
LO[user].ff = false;
if (out === false) {
Bot.say(room, `/sendhtmlpage ${by}, Lights Out (${by.substr(1)}), ${header + LO[user].boardHTML(true)}`);
LO[user].spectators.forEach(p => Bot.say(room, `/sendhtmlpage ${p}, Lights Out (${by.substr(1)}), ${header + LO[user].boardHTML()}`));
return;
}
if (out === true) {
Bot.say(room, `/sendhtmlpage ${by}, Lights Out (${by.substr(1)}), ${header + LO[user].boardHTML()}<br /><br /><h1 style="text-align: center;">Done! Congratulations!</h1>`);
LO[user].spectators.forEach(p => Bot.say(room, `/sendhtmlpage ${p}, Lights Out (${by.substr(1)}), ${header + LO[user].boardHTML()}`));
if (LO[user].size.reduce((a, b) => a * b, 1) < 25) Bot.roomReply(room, by, `You solved it in ${LO[user].moves.length} moves! (My solution was ${LO[user].soln.length} moves)`);
else {
Bot.say(room, `/adduhtml Lights Out @ ${Date.now()}, ${LO[user].boardHTML(false, LO[user].problem, true)}`);
Bot.say(room, `${by.substr(1)} solved this in ${LO[user].moves.length} moves! (My solution was ${LO[user].soln.length} moves)`);
}
const smugUsers = ['asxier', 'aegii', 'partoru', 'tanpat'];
if (smugUsers.includes(user) && LO[user].soln.length < LO[user].moves.length) Bot.roomReply(room, by, `PFFFT IMAGINE LOSING TO A BOT`);
delete LO[user];
return;
}
Bot.say(room, "AAAAAA");
Bot.log(LO);
break;
}
case 'spectate': case 's': case 'watch': case 'w': {
if (!args.length) return Bot.roomReply(room, by, "Err, whose game do you want to watch?");
player = toID(args.join(''));
if (!LO[player]) return Bot.roomReply(room, by, `I couldn't find a listed game for ${player}.`);
if (player === user) return Bot.roomReply(room, by, ">spectating your own game what");
if (LO[player].spectators.includes(user)) return Bot.roomReply(room, by, "You're already spectating! Try using unspectate if you don't want to spectate.");
if (LO[player].size.reduce((a, b) => a * b, 1) < 25) return Bot.roomReply(room, by, "Due to flooding, spectating has been disabled for smaller games.");
LO[player].spectators.push(user);
Bot.roomReply(room, by, `You're now spectating ${LO[player].name}'s game!`);
const header = `<div style="display: inline-block; float: left; font-weight: bold;">My Solution: ${LO[player].soln.length} moves</div><div style="display: inline-block; float: right; font-weight: bold;">Moves Made: ${LO[player].moves.length} moves</div><br /><br /><br />`;
Bot.say(room, `/sendhtmlpage ${by}, Lights Out (${player}), ${header + LO[player].boardHTML()}`);
break;
}
case 'unspectate': case 'us': case 'unwatch': case 'uw': {
if (!args.length) {
const ind = Object.values(LO).find(game => game.spectators.includes(user));
if (ind) args = [ind];
else return Bot.roomReply(room, by, "Err, whose game do you want to stop watching?");
}
player = toID(args.join(''));
if (!LO[player]) return Bot.roomReply(room, by, `I couldn't find a listed game for ${player}.`);
if (!LO[player].spectators.includes(user)) return Boy.pm(by, "You're not spectating...");
LO[player].spectators.remove(user);
Bot.roomReply(room, by, `You are no longer spectating ${LO[player].name}'s game... :(`);
break;
}
case 'rejoin': case 'rj': {
if (args.length) user = toID(args.join(''));
if (!LO[user]) return Bot.roomReply(room, by, `Could not join ${user}'s game.`);
const header = `<div style="display: inline-block; float: left; font-weight: bold;">My Solution: ${LO[user].soln.length} moves</div><div style="display: inline-block; float: right; font-weight: bold;">Moves Made: ${LO[user].moves.length} moves</div><br /><br /><br />`;
if (user === toID(by)) return Bot.say(room, `/sendhtmlpage ${by}, Lights Out (${by.substr(1)}), ${header + LO[user].boardHTML(true)}`);
if (LO[user].spectators.includes(toID(by))) return Bot.say(room, `/sendhtmlpage ${by}, Lights Out (${player}), ${header + LO[player].boardHTML()}`);
return Bot.roomReply(room, by, "Err, you werent' a spectator there.");
break;
}
case 'forfeit': case 'f': case 'ff': case 'resign': {
if (!LO[user]) return Bot.roomReply(room, by, "Life sometimes throws you a curveball. Doesn't mean you need to forfeit. And definitely not without trying.");
if (!LO[user].ff) {
Bot.roomReply(room, by, "Are you sure you want to forfeit? If you are, use this again.");
LO[user].ff = true;
return;
}
Bot.roomReply(room, by, "F, ended.");
// Bot.say(room, `/adduhtml Lights Out @ ${Date.now()}, ${LO[user].boardHTML(false, LO[user].problem)}`);
// Bot.say(room, `^ solvable in ${LO[user].soln.length} moves.`);
delete LO[user];
return;
break;
}
}
}
};
<file_sep>/discord/guess.js
const PZ = require('../data/PUZZLES/index.js');
module.exports = {
help: `Makes a guess for an unlocked puzzle.`,
guildOnly: [PZ.guildID, '871207224054272041'],
commandFunction: function (args, message, Bot) {
if (message.guild.id === '871207224054272041') {
if (!['888995370238103582' /* Code channel*/, '889548319238549514', '889548317338505256'].includes(message.channel.id)) {
return message.channel.send("You don't look like a Death Match candidate...");
}
const obj = Bot.gtmm;
if (!obj) return message.channel.send(`Hasn't started yet!`);
const codes = { '888995370238103582': '12345', '889548319238549514': '74737', '889548317338505256': '12345' };
const code = codes[message.channel.id].split('').map(n => ~~n);
let input = toID(args.join(''));
if (['status', 'guesses', 'history', 'list', 'past'].includes(input)) {
const guesses = message.channel.guesses;
if (!guesses.length) return message.channel.send(`You haven't made any guesses yet!`);
const emotes = [
'0️⃣', '1️⃣', '2️⃣', '3️⃣',
'4️⃣', '5️⃣', '6️⃣', '7️⃣',
'8️⃣', '9️⃣'
];
const rgs = guesses.slice().reverse().map((guess, i) => {
return `${guess[0].map(t => emotes[t]).join('')} | ${guess[1][0]} 🔴 | ${guess[1][1]} ⚪ | #${guesses.length - i}`;
});
message.channel.send(`Your guesses:\n\n${rgs.join('\n')}`);
return;
} else input = String(input).replace(/[^\d]/g, '').split('').map(num => ~~num);
if (obj[message.channel.id]) {
return message.channel.send(`Cooling down! ${tools.toHumanTime(obj[message.channel.id] - Date.now())} left.`);
}
if (!message.channel.guesses) message.channel.guesses = [];
if (message.channel.alreadyGuessed) {
return message.channel.send(`But you already solved it in ${message.channel.guesses.length} tries!`);
}
if (input.length !== 5) return message.channel.send("Guess must be 5 numbers long!");
let sol = code.slice(), guess = input.slice(), close = 0;
const hits = [];
for (let i = 0; i < 5; i++) {
if (sol[i] === guess[i]) hits.push(i);
}
if (hits.length === 5) {
// Correct guess
message.channel.guesses.push([input, [5, 0]]);
// eslint-disable-next-line
message.channel.send(`You were correct! The code was ${code.join('')}, and you guessed it in ${message.channel.guesses.length} tries!`);
client.channels.cache.get('906389929930682388').send(`<@!${message.author.id}> successfully guessed the code!`);
message.channel.alreadyGuessed = true;
return;
}
sol = sol.filter((t, i) => !hits.includes(i)).sort((a, b) => a - b);
guess = guess.filter((t, i) => !hits.includes(i)).sort((a, b) => a - b);
for (let i = 0; i < sol.length; i++) {
while (sol.includes(guess[i])) {
sol.remove(guess[i]);
guess.remove(guess[i]);
close++;
}
}
message.channel.guesses.push([input, [hits.length, close]]);
// eslint-disable-next-line
message.channel.send(`You guessed \`${input.join('')}\` - ${hits.length} ${hits.length === 1 ? 'was' : 'were'} correct and in the right position, and ${close} ${close === 1 ? 'was' : 'were'} correct but in the wrong position.`);
const endTime = Date.now() + 25 * 1000;
obj[message.channel.id] = endTime;
setTimeout(() => delete obj[message.channel.id], 25 * 1000);
return;
}
if (!PZ.live) return message.channel.send("Sorry, this command may not be used at this time. 'o.o");
const team = PZ.getTeam(message.member);
if (!team) return message.channel.send("You don't seem to be participating... maybe contact one of our staff?");
if (team.channel !== message.channel.id) {
return message.channel.send("Please only use this in your own team's channel.").then(msg => {
msg.delete({ timeout: 3000 });
message.delete({ timeout: 30 });
});
}
if (!args.length) return message.channel.send("Which puzzle?");
const cargs = args.join(' ').split(/\s*,\s*/);
if (cargs.length < 2) {
// eslint-disable-next-line
return message.channel.send(`Unexpected number of arguments - the correct syntax is \`${prefix}guess (puzzle ID), (your guess)\``);
}
const puzzle = PZ.getPuzzle(cargs.shift());
const guess = cargs.join(',');
if (!puzzle || !team.unlocked.includes(puzzle.index)) {
return message.channel.send("Puzzle not found.");
}
PZ.guess(team, puzzle, guess).then(res => {
if (res) {
message.channel.send(`The correct answer was, indeed, ${puzzle.solution}!`);
if (puzzle.index === "M") {
message.channel.send(`**Congratulations! You have solved the metapuzzle!**`);
} else {
require('./puzzles.js').commandFunction([], message, Bot);
}
} else message.channel.send("Sorry, doesn't look like that was the answer...");
}).catch(e => message.channel.send(e));
}
};
<file_sep>/commands/2v2/dpp.js
module.exports = {
cooldown: 10000,
help: `Displays the DPP 2v2 GC link.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `<<groupchat-2v2-dpp2v2>>`);
}
};
<file_sep>/commands/petsanimals/addpic.js
module.exports = {
cooldown: 0,
help: `Adds an image URL to your pets display!`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `/me hugs its zxc`);
const DB = Bot.DB('pets');
const [pet, url] = args.join(' ').split(/[,]/);
if (!pet || !url) return Bot.roomReply(room, by, `You need to specify both the pet's name and the image link!`);
// Test the image
axios.head(url).then(res => {
if (!res.headers['content-type'].match(/image\/(?:png|jpeg|webp|gif)/)) {
return Bot.roomReply(room, by, `Errm apparently the link you sent isn't an image URL`);
}
const user = toID(by);
const obj = DB.get(user);
if (!obj) obj = {};
const petID = toID(pet);
if (!obj.pets?.[petID]) {
// eslint-disable-next-line max-len
return Bot.roomReply(room, by, `You need to register the pet first before adding pics! Use the \`\`${prefix}addpet\`\` command for this!`);
}
obj.pets[petID].images?.push(url);
DB.set(user, obj);
Bot.say(room, `!show ${url}, Added!`);
}).catch((err) => {
Bot.log(err);
Bot.roomReply(room, by, `Invalid image URL! (Please don't tell me I'm being bad`);
});
}
};
<file_sep>/commands/groupchat-battledome-winterexplorers/gameplan.js
module.exports = {
cooldown: 1,
help: ``,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
// eslint-disable-next-line max-len
Bot.say(room, `/addhtmlbox Current gameplan:<br />a) <strike>KILL FROZEN WATER</strike> Apparently not doable :sad:<br />b) DON'T DIE UNTIL YOU'RE KILLED<br />c) WIN<br />d) Ranges: Line 6 AoE, Line 5, Cone 2 AoE, Melee Splash, Global splash on Lava<br />e) YAY 3/5 EVASIONS AND NOT 0/8<br />f) CRES IS UP, BATH WILL WH`);
}
};
<file_sep>/pmcommands/ports.js
module.exports = {
help: `Displays the available ports for a term.`,
permissions: 'coder',
commandFunction: function (Bot, by, args, client) {
if (!args.length) return Bot.pm(by, 'Uhh, what ports should I get?');
const out = {};
const sources = {
"Pokemon": Object.values(data.pokedex).map(m => m.name),
"Moves": Object.values(data.moves).map(m => m.name),
"Items": Object.values(data.items).map(i => i.name).map(name => name.replace(/ Berry$/, '')),
"Abilities": data.abilities,
"Locations": []
};
const terms = args.join(' ').split(/\s*,\s*/), term = toID(terms.shift());
Object.keys(sources).forEach(type => out[type] = tools.getPorts(term, sources[type]));
let front = `<details><summary>Front</summary><hr>`;
const types = Object.keys(out).filter(type => out[type][0] && out[type][0].length);
types.forEach(type => front += `<details><summary>${type}</summary>${out[type][0].join('<br>')}<hr></details>`);
if (!types.length) front += 'None.';
front += '<hr></details>';
let end = `<details><summary>End</summary><hr>`;
const eTypes = Object.keys(out).filter(type => out[type][1] && out[type][1].length);
eTypes.forEach(type => end += `<details><summary>${type}</summary>${out[type][1].join('<br>')}<hr></details>`);
if (!eTypes.length) end += 'None.';
end += '<hr></details>';
return Bot.sendHTML(by, front + '<br>' + end);
}
};
<file_sep>/commands/global/mastermind.js
module.exports = {
help: `Mastermind, the code-breaking game! Type \`\`${prefix}mastermind new (guess limit, optional)\`\` to make a game. Rules: https://docs.google.com/document/u/1/d/e/2P<KEY>6D3sg-TS5ya-MO<KEY>`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client, pm) {
if (!tools.canHTML(room) && !room.startsWith('groupchat-')) {
return Bot.say(room, "Sorry, can't do that here - I need to be a room Bot.");
}
let user;
if (!args.length) args.push('help');
switch (toID(args.shift())) {
case 'help': case 'h': {
if (tools.hasPermission(by, 'gamma', room) && !pm) return Bot.say(room, this.help);
else return Bot.roomReply(room, by, this.help);
break;
}
case 'new': case 'n': {
if (!Bot.rooms[room].mastermind) Bot.rooms[room].mastermind = {};
const mm = Bot.rooms[room].mastermind;
user = toID(by);
if (mm[user]) return Bot.roomReply(room, by, `You're already playing one! If you want to end the current one, do \`\`${prefix}mastermind end\`\`.`);
if (pm) return Bot.roomReply(room, by, "Can't start one from PMs. o.o");
let limit;
if (args.length) limit = parseInt(args);
if (limit && !(limit < 13 && limit > 4)) {
Bot.roomReply(room, by, "Invalid limit; limit has been set to 10.");
limit = 10;
}
if (!limit) limit = 10;
mm[user] = GAMES.create('mastermind', room, by, limit);
Bot.say(room, `/adduhtml MM${user},<hr/>${by.substr(1)} is playing a round of Mastermind! <button name="send" value="/botmsg ${Bot.status.nickName}, ${prefix}mastermind ${room} watch ${user}">Watch</button><br/><br/><form data-submitsend="/msgroom ${room}, /botmsg ${Bot.status.nickName},${prefix}mastermind ${room} setcode ${user}, {code}"><label for="choosecode">Set Code: </label><input type="text" id="choosecode" name="code" style="width: 30px;"> <input type="submit" value="Set"/></form><hr/>`);
mm[user].sendPages();
return;
break;
}
case 'guess': case 'g': case 'play': case 'p': {
if (!Bot.rooms[room].mastermind) return Bot.roomReply(room, by, "No games are active.");
const mm = Bot.rooms[room].mastermind;
user = toID(by);
if (!mm[user]) return Bot.roomReply(room, by, "You're not playing...");
if (!args.length) return Bot.roomReply(room, by, unxa);
const guess = args.join('').replace(/[^0-7]/g, '');
if (guess.length !== 4) {
mm[user].sendPages(true);
return Bot.roomReply(room, by, "Invalid guess - your guess must contain four valid numbers from 0-7.");
}
return mm[user].guess(guess).then(end => {
switch (end) {
case 0: {
if (mm[user].guesses.length === 1) Bot.say(room, `/changeuhtml MM${user}, <hr/>${tools.escapeHTML(by.substr(1))} is playing a round of Mastermind! <button name="send" value="/botmsg ${Bot.status.nickName},${prefix}mastermind ${room} watch ${user}">Watch</button><hr/>`);
return mm[user].sendPages();
break;
}
case 1: {
Bot.say(room, `/changeuhtml MM${user}, <hr/>${tools.escapeHTML(by.substr(1))} is playing a round of Mastermind!<hr/>`);
Bot.say(room, `${by.substr(1)} successfully cracked ${mm[user].sol.join('')} in ${mm[user].guesses.length} tr${mm[user].guesses.length === 1 ? 'y' : 'ies'}!`);
mm[user].sendPages();
return delete mm[user];
break;
}
case 2: {
Bot.say(room, `/changeuhtml MM${user}, <hr/>${tools.escapeHTML(by.substr(1))} is playing a round of Mastermind!<hr/>`);
Bot.say(room, `${by.substr(1)} was unable to crack ${mm[user].sol.join('')} in ${mm[user].guesses.length} tries. ;-;`);
mm[user].sendPages();
return delete mm[user];
break;
}
}
}).catch(err => {
Bot.roomReply(room, by, err);
mm[user].sendPages();
});
break;
}
case 'setcode': {
if (!Bot.rooms[room].mastermind) return Bot.roomReply(room, by, "No games are active.");
const mm = Bot.rooms[room].mastermind;
const [target, code] = args.join(' ').split(',').map(toID);
if (!target || !/^[0-7]{4}$/.test(code)) return Bot.roomReply(room, by, 'Welp, that wasn\'t a valid code - try again in another match!');
if (!mm.hasOwnProperty(target)) return Bot.roomReply(room, by, "Don't have anyone by that name playing");
const game = mm[target];
if (game.forced) return Bot.roomReply(room, by, `This game's code has already been set.`);
if (game.guesses.length) return Bot.roomReply(room, by, `They've already started answering - try a bit faster next time!`);
if (target === toID(by)) return Bot.roomReply(room, by, `You have set the code to ${code[0]}- WAIT A MINUTE THIS IS YOU`);
const old = game.sol.join('');
game.sol = code.split('').map(num => ~~num);
game.forced = toID(by);
Bot.roomReply(room, by, `You have set the code to ${code}`);
Bot.say(room, `${by.substr(1)} has chosen a code for ${target}!`);
Bot.say(room, `/changeuhtml MM${target}, <hr/>${tools.escapeHTML(game.name)} is playing a round of Mastermind! <button name="send" value="/botmsg ${Bot.status.nickName},${prefix}mastermind ${room} watch ${target}">Watch</button><hr/>`);
break;
}
case 'spectate': case 's': case 'watch': case 'w': {
if (!Bot.rooms[room].mastermind) return Bot.roomReply(room, by, "No games are active.");
const mm = Bot.rooms[room].mastermind;
user = toID(by);
let input;
if (!Object.keys(mm).length) return Bot.roomReply(room, by, "NOBODY. NOBODY AT ALL.");
if (Object.keys(mm).length === 1) input = Object.keys(mm)[0];
if (args.length) input = toID(args.join(''));
if (!mm[input]) return Bot.roomReply(room, by, `Sorry, didn't find ${input ? `${input}'s` : 'a'} game.`);
if (mm[input].spectators.includes(user)) return Bot.roomReply(room, by, "You're already spectating them - use rejoin to rejoin if you accidentally closed it, or unspectate to stop spectating.");
if (mm[input].player === user) return Bot.roomReply(room, by, "Mirror, mirror, on the wall - who's the nerdiest of 'em all?");
mm[input].spectators.push(user);
Bot.roomReply(room, by, `You're now spectating ${mm[input].name}'s game of Mastermind!`);
Bot.say(room, `/sendhtmlpage ${user}, Mastermind + ${room} + ${input},${mm[input].boardHTML()}`);
break;
}
case 'unspectate': case 'us': case 'unwatch': case 'uw': case 'u': {
if (!Bot.rooms[room].mastermind) return Bot.roomReply(room, by, "No games are active.");
const mm = Bot.rooms[room].mastermind;
user = toID(by);
let input;
if (!Object.keys(mm).length) return Bot.roomReply(room, by, "NOBODY. NOBODY AT ALL.");
const games = Object.values(mm).filter(game => game.spectators.includes(user));
if (games.length === 1) input = games[0].player;
if (args.length) input = toID(args.join(''));
if (!mm[input]) return Bot.roomReply(room, by, `Sorry, didn't find ${input}'s game.`);
if (!mm[input].spectators.includes(user)) return Bot.roomReply(room, by, "You arne't spectating them - use the spectate option to spectate.");
if (mm[input].player === user) return Bot.roomReply(room, by, "Mirror, mirror, on the wall - who's the nerdiest of 'em all?");
mm[input].spectators.remove(user);
Bot.roomReply(room, by, `You are no longer spectating ${mm[input].name}'s game of Mastermind. ;-;`);
break;
}
case 'rejoin': case 'rj': {
if (!Bot.rooms[room].mastermind) return Bot.roomReply(room, by, "No games are active.");
const mm = Bot.rooms[room].mastermind;
user = toID(by);
if (!mm[user]) return Bot.roomReply(room, by, "You're not playing...");
const users = [];
Object.values(mm).forEach(game => {
if (game.spectators.includes(user) || game.player === user) users.push(game.player);
});
users.forEach(game => Bot.say(room, `/sendhtmlpage ${user}, Mastermind + ${room} + ${game},${mm[game].boardHTML(mm[game].player === user)}`));
break;
}
case 'forfeit': case 'ff': case 'f': case 'resign': case 'r': case 'end': case 'e': {
if (!Bot.rooms[room].mastermind) return Bot.roomReply(room, by, "No games are active.");
const mm = Bot.rooms[room].mastermind; user = toID(by);
if (!mm[user]) return Bot.roomReply(room, by, "You're not playing...");
Bot.say(room, `${by.substr(1)} was unable to crack ${mm[user].sol.join('')} in ${mm[user].guesses.length} tries. ;-;`);
return delete mm[user];
break;
}
case 'type': case 't': {
if (!Bot.rooms[room].mastermind) return Bot.roomReply(room, by, "No games are active.");
const mm = Bot.rooms[room].mastermind;
user = toID(by);
if (!mm[user]) return Bot.roomReply(room, by, "You're not playing...");
if (!args.length) return Bot.roomReply(room, by, unxa);
const guess = args.join('').replace(/[^0-7]/g, '');
if (guess.length !== 1) return Bot.roomReply(room, by, "Invalid - your message must contain exactly one valid number from 0-7.");
if (!mm[user].type(...guess)) {
Bot.log(mm[user]);
return Bot.roomReply(room, by, "Something went wrong!");
}
return mm[user].sendPages();
break;
}
case 'backspace': case 'b': {
if (!Bot.rooms[room].mastermind) return Bot.roomReply(room, by, "No games are active.");
const mm = Bot.rooms[room].mastermind;
user = toID(by);
if (!mm[user]) return Bot.roomReply(room, by, "You're not playing...");
if (mm[user].backspace()) mm[user].sendPages();
return;
break;
}
default: {
Bot.roomReply(room, by, "Sorry, I don't get what you want me to do. Take a hug instead.");
}
}
}
};
<file_sep>/discord/reportmatch.js
/* eslint-disable no-unreachable */
module.exports = {
help: `Begins a match report`,
pm: true,
admin: true,
commandFunction: function (args, message, Bot) {
return;
const link = args.join(' ')
.match(/https?:\/\/play\.pokemonshowdown.com\/(battle-(gen8randombattle-\d{10,11})-[a-z0-9]{31}pw)/);
if (!link) return message.channel.send(`No valid URL found.`);
const [url, fullLink, battleRoom] = link;
if (!Bot.reportMatches) Bot.reportMatches = {};
if (!Bot.joiningBattles) Bot.joiningBattles = {};
Bot.joiningBattles[battleRoom] = true;
}
};
<file_sep>/discord/hints.js
const PZ = require('../data/PUZZLES/index.js');
module.exports = {
help: `Displays the available number of hints.`,
guildOnly: PZ.guildID,
commandFunction: function (args, message, Bot) {
if (!PZ.live) return message.channel.send("Sorry, this command may not be used at this time. 'o.o");
const team = PZ.getTeam(message.member);
if (!team) return message.channel.send("You don't seem to be participating... maybe contact one of our staff?");
if (team.channel !== message.channel.id) {
return message.channel.send("Please only use this in your own team's channel.").then(msg => {
msg.delete({ timeout: 3000 });
message.delete({ timeout: 3000 });
});
}
const Discord = require('discord.js'), embed = new Discord.MessageEmbed();
embed.addField('Hints available:', team.hints).setColor('#F1C40F');
message.channel.send(embed);
}
};
<file_sep>/discord/finduser.js
module.exports = {
help: `Does stuff.`,
admin: true,
commandFunction: function (args, message, Bot) {
const name = args.join(' ').trim();
const users = message.guild.members.cache.filter(m => m.displayName === name);
if (!users.size) return message.channel.send("Couldn't find 'em.");
return message.channel.send(users.map(user => `<@${user.user.id}>`).join(', '));
}
};
<file_sep>/pmcommands/modnote.js
module.exports = {
help: `Modnote features. Syntax: ${prefix}modnote (room), (text)`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
const cargs = args.join(' ').split(',');
if (cargs.length < 2) return Bot.pm(by, unxa);
const room = tools.getRoom(cargs.shift());
if (!room || !Bot.rooms[room]) return Bot.pm(by, "I don't seem to be in that room.");
if (!tools.canHTML(room)) return Bot.pm(by, "I don't have the permissions for this, sorry. I need to be roombot.");
if (!tools.hasPermission(by, 'beta', room)) return Bot.pm(by, "This command can only be used by roomstaff");
const user = Bot.rooms[room].users.find(u => toID(u) === toID(by));
if (!user) return Bot.pm(by, `You're not roomstaff; only roomstaff have permission to use this.`);
const name = user.substr(1).replace(/@!$/, '').replace(/</g, '<');
// eslint-disable-next-line max-len
Bot.say(room, `/addrankhtmlbox *, <div class="chat chatmessage-partbot" style="display:inline-block;"><small>[MODNOTE] ${user[0]}</small>${tools.colourize(name + ':').replace(name, `<span class="username" data-roomgroup="${user[0]}" data-name="${user.substr(1)}">${name}</span>`)}<em> ${cargs.join(',').replace(/</g, '<')}</em></div><br/><span style='color:#444444;font-size:10px'>Note: Only users ranked % and above can see this.</span>`);
// eslint-disable-next-line max-len
Bot.say(room, `/sendhtmlpage ${by},modnote-${room},<center><form data-submitsend="/msgroom ${room},/botmsg ${Bot.status.nickName},${prefix}mn ${room}, {msg}"><br/><br/><input name="msg" type="text" style="width:500px"><br/><br/><input type="submit" value="Modnote" name="Modnote"></form></center>`);
}
};
<file_sep>/discord/s.js
module.exports = {
help: `Speaks.`,
admin: true,
guildOnly: ['719076445699440700'],
commandFunction: function (args, message, Bot) {
const content = args.join(' ');
// eslint-disable-next-line
Bot.say(message.channel.name, `/adduhtml pbspeaks${Date.now()},${tools.quoteParse(`[00:00:00] +PartMan: ${content}`)}<div style="margin-bottom:0;padding-bottom:0;position:relative;top:-17px;float:right;color:gray;font-size:0.8em;height:0px;" null="></div>"`);
}
};
<file_sep>/commands/global/me.js
module.exports = {
cooldown: 1000,
help: `Displays your permissions level. Order: Admin > Coder > Alpha > Beta > Gamma > Pleb > Locked.`,
permissions: 'locked',
commandFunction: function (Bot, room, time, by, args, client) {
if (args[0]) return Bot.say(room, unxa);
const rank = tools.rankLevel(by, room);
let role;
switch (rank) {
case 1:
role = 'Locked.';
break;
case 2:
role = 'muted.';
break;
case 3:
role = 'a regular ol\' Joe.';
break;
case 4:
role = 'a Gamma.';
break;
case 5:
role = 'a Beta.';
break;
case 6:
role = 'an Alpha.';
break;
case 9:
role = 'a Coder.';
break;
case 10:
role = 'a Bot Administrator.';
break;
default:
role = 'somehow screwing up the Bot code. Definitely not PartMan\'s fault.';
break;
}
if (rank < 4) Bot.pm(by, 'You are ' + role);
else Bot.say(room, 'You are ' + role);
}
};
<file_sep>/commands/global/stay.js
module.exports = {
cooldown: 10,
help: `Used to stay in Blackjack. Syntax: ${prefix}stay`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
if (!Bot.rooms[room].blackjack) return Bot.roomReply(room, by, 'No game of Blackjhack is currently active...');
if (Bot.rooms[room].blackjack.turn !== toID(by)) return Bot.roomReply(room, by, `It's not your turn.`);
const user = Bot.rooms[room].blackjack.players[toID(by)];
if (tools.sumBJ(user.cards) === 21) {
if (user.cards.length === 2) user.nbj = true;
Bot.say(room, `${user.name} has a Blackjack!`);
}
return Bot.rooms[room].blackjack.nextTurn(room);
}
};
<file_sep>/pmcommands/rttt.js
module.exports = {
help: `Hunt Board Games roomauth!`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
return Bot.pm(by, `B-but UGO is over!`);
// eslint-disable-next-line no-unreachable
const userID = toID(by);
if (!tools.hasPermission(by, 'boardgames', 'gamma') || Bot.rooms.boardgames?.users.find(u => toID(u) === userID)?.test(/^ /)) {
return Bot.pm(by, `Access denied - please ask the auth member to PM me \`\`${prefix}rttt ${toID(by)}\`\``);
}
const targetID = toID(args.join(''));
const target = Bot.rooms.boardgames?.users.find(u => toID(u) === targetID)?.replace(/@!$/, '').substr(1);
if (!target) return Bot.pm(by, `Unable to find the target in Board Games!`);
const user = by.substr(1).replace(/@!$/, '');
// eslint-disable-next-line max-len
Bot.say('boardgames', `/sendhtmlpage ${user}, RTTT-${target}-${user}, <center><button name="send" value="/msgroom boardgames,/botmsg ${Bot.status.nickName},${prefix}rttts ${target},X" style="font-size:1.5em;background:none;padding:20px;color:inherit;border:1px solid;border-radius:10px;margin:50px"><username>${target}</username>: X<br/><username>${user}</username>: O</button name="send" value="/msgroom boardgames,/botmsg ${Bot.status.nickName},${prefix}rttts ${target},X"><button name="send" value="/msgroom boardgames,/botmsg ${Bot.status.nickName},${prefix}rttts ${target},O" style="font-size:1.5em;background:none;padding:20px;color:inherit;border:1px solid;border-radius:10px;margin:50px"><username>${target}</username>: O<br/><username>${user}</username>: X</button name="send" value="/msgroom boardgames,/botmsg ${Bot.status.nickName},${prefix}rtttstart ${target}, "></center>`);
}
};
<file_sep>/discord/hotpatch.js
module.exports = {
help: `Hotpatches stuff.`,
admin: true,
commandFunction: function (args, message, Bot) {
if (!args.length) return message.channel.send(unxa).then(msg => msg.delete({ timeout: 3000 }));
Bot.hotpatch(args.join(' '), message.author.username)
.then(out => message.channel.send(`Successfully hotpatched: ${out}.`))
.catch(e => message.channel.send(`Hotpatch failed: ${e}`));
}
};
<file_sep>/commands/groupchat-partbot-1v1tc/bans7.js
module.exports = {
cooldown: 1000,
help: `Displays the bans for a type.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
if (!args[0]) args = ['all'];
const ftype = toID(args.join(' '));
if (!typelist.includes(ftype) && !(ftype == 'all')) return Bot.say(room, 'Invalid type.');
if (ftype == 'all') {
let out = '';
typelist.forEach(type => {
out += 'TC ' + tools.colourize(tools.toName(type)) + ' Banlist: ';
const bans = require('../../data/VR/TC7/' + type + '.js')[type].bans;
if (bans.length) out += bans.join(', ');
else out += 'None';
out += '<BR>';
});
if (tools.hasPermission(by, 'gamma')) return Bot.say(room, '/adduhtml BANS, ' + out);
else return Bot.say(room, '/pminfobox ' + by + ', ' + out);
}
const bans = require('../../data/VR/TC7/' + ftype + '.js')[ftype].bans;
return Bot.say(room, 'TC ' + tools.toName(ftype) + ' Banlist: ' + (bans.length ? bans.join(', ') : 'None'));
}
};
<file_sep>/handlers/tours.js
// TODO: Emit events
module.exports = function (room, tourData, Bot) {
if (tourData?.[0] === 'create') {
// if (room === 'hindi') setTimeout(() => Bot.rooms.hindi.tourPinged = false, 10 * 60 * 1000);
try {
const roomData = require(`../data/ROOMS/${room}.json`);
if (roomData.tour && ['*', '#', '★'].includes(Bot.rooms[room].rank)) {
setTimeout(() => {
Bot.say(room, `/tour autostart ${roomData.tour[0]}\n/tour autodq ${roomData.tour[1]}`);
}, roomData.tour[2] || 2000);
}
} catch {}
}
if (room === 'hindi') {
if (!tourData) return;
if (tourData[0] === 'battlestart') {
Bot.say('', '/j ' + tourData[3]);
return setTimeout((room, text) => Bot.say(room, text), 1000, tourData[3], `G'luck!\n/part`);
} else if (tourData[0] === 'update') {
try {
const json = JSON.parse(tourData[1]);
if (json.generator !== 'Single Elimination') return;
if (!json.bracketData) return;
if (json.bracketData.type !== 'tree') return;
if (!json.bracketData.rootNode) return;
if (json.bracketData.rootNode.state === 'inprogress') {
Bot.say(room, `/wall Tour finals! <<${json.bracketData.rootNode.room}>>`);
}
} catch (e) {
Bot.log(e);
}
} else if (tourData[0] === 'end') {
try {
const json = JSON.parse(tourData[1]);
if (json.generator !== 'Single Elimination') return;
if (/casual|ignore|no ?points/i.test(json.format || '')) return;
if (json.bracketData.type !== 'tree') return;
// The actual algorithm is secret
// Nice try, though
Bot.commandHandler('leaderboard', '#PartMan', [], room);
} catch (e) {
Bot.log(e);
}
}
}
if (room === 'groupchat-botdevelopment-p') {
Bot.log(tourData);
}
};
<file_sep>/pmcommands/genport.js
module.exports = {
help: `Generates a port with a given length. Defaults to 6 terms.`,
permissions: 'coder',
commandFunction: function (Bot, by, args, client) {
let num = parseInt(args.join('').replace(/[^0-9]/g, ''));
if (isNaN(num) || num < 2) num = 6;
const toWord = {};
Object.values(data.pokedex).forEach(term => toWord[toID(term.name)] = term.name);
Object.values(data.moves).forEach(term => toWord[toID(term.name)] = term.name);
Object.values(data.items).map(term => {
return term.name.endsWith(' Berry') ? term.name.substr(0, term.name.length - 6) : term.name;
}).forEach(term => toWord[toID(term)] = term);
data.abilities.forEach(term => toWord[toID(term)] = term);
const words = Object.keys(toWord);
let port = [words.random()];
let i = 0;
while (++i < num) {
const terms = tools.getPorts(port[port.length - 1], words)[1];
if (terms.length === 1) {
Bot.log("Backtracked: " + port.pop());
// port.pop();
i--;
if (!port.length) port.push(words.random());
continue;
}
let term;
while (!term || term === port[port.length - 1]) term = terms.random();
port.push(term);
}
port = port.map(term => toWord[term]);
const text = port.join(', ');
if (text.length < 250) return Bot.pm(by, text);
else tools.uploadToPastie(text).then(url => Bot.pm(by, url));
}
};
<file_sep>/pmcommands/removefromraid.js
module.exports = {
noDisplay: true,
help: `Adds a user to a hosted raid.`,
permissions: 'none',
commandFunction: function (Bot, by, args, client) {
const room = 'pokemongo';
if (!Bot.rooms[room]?.users.some(u => toID(u) === toID(by))) return Bot.pm(by, '<<pokemongo>>');
return Bot.commandHandler('removefromraid', by, args, room, true);
}
};
<file_sep>/commands/global/leave.js
module.exports = {
cooldown: 10,
help: `Leaves a room`,
permissions: 'coder',
commandFunction: function (Bot, room, time, by, args, client) {
Bot.say(room, `/me pouts\n/part`);
}
};
<file_sep>/data/BATTLE/ai.js
class game {
constructor (room, side) {
if (!room) return null;
this.room = room;
this.side = side;
this.ai = 2;
this.active = null;
this.enemy = null;
this.enemyTeam = [];
this.started = false;
this.tier = null;
this.setHazards = {};
this.sideHazards = {};
this.enemyData = {
boosts: {
atk: 0,
def: 0,
spa: 0,
spd: 0,
spe: 0
},
ability: null,
item: null
};
this.selfBoosts = {
atk: 0,
def: 0,
spa: 0,
spd: 0,
spe: 0
};
}
random (obj) {
if (typeof obj !== 'object') return console.log('Wrong input for random.');
let seed = Math.random() * Object.values(obj).reduce((a, b) => a + b, 0);
for (const val in obj) {
seed -= obj[val];
if (seed < 0) return val;
}
return null;
}
getMon (name) {
for (const mon of this.side.pokemon) {
if (!mon) return;
if (mon.ident === name) return mon;
}
return null;
}
getActive () {
for (const mon of this.side.pokemon) {
if (!mon) return;
if (mon.active) return mon;
}
return null;
}
getIndex (name) {
for (let i = 0; i < this.side.pokemon.length; i++) {
const mon = this.side.pokemon[i];
if (!mon) continue;
if (mon.ident === name) return i;
}
return -1;
}
moveWt (name, mon, moves) {
const move = data.moves[toID(name)];
if (!moves) moves = [];
if (!move || !mon) return 0.001;
let bp = 0;
if (move.basePower) bp += move.basePower;
if (move.boosts && move.target === 'self') {
if (move.boosts.atk > 0 || move.boosts.spa > 0) {
const stat = move.boosts.atk > move.boosts.spa ? 'atk' : 'spa';
if (
!(stat === 'atk' && !moves.map(toID).filter(move => data.moves[move]?.category === 'Physical').length) &&
!(stat === 'spa' && !moves.map(toID).filter(move => data.moves[move]?.category === 'Special').length)
) bp += ((6 - this.selfBoosts[stat]) * move.boosts[stat] * 200) ** 0.5;
}
if (move.boosts.spe) bp += ((6 - this.selfBoosts.spe) * move.boosts.spe * 200) ** 0.5;
}
if (move.target === 'normal' && move.self && move.self.boosts) {
bp += ((6 - this.selfBoosts.spe) * (move.self.boosts.spe || 0) * 200) ** 0.5;
}
if (move.secondary && move.secondary.self && move.secondary.self.boosts) {
['atk', 'spa', 'spe'].forEach(boost => {
bp += ((6 - this.selfBoosts[boost]) * (move.secondary.self.boosts[boost] || 0)) ** 20;
});
}
if (
this.enemy &&
(this.enemyData.item === 'Air Balloon' || this.enemyData.ability === 'Levitate') &&
move.type === 'Ground' && move.Category !== 'Status'
) return 0.5;
if (
this.enemy &&
Object.values(data.pokedex[toID(this.enemy)].abilities).includes('Levitate') &&
move.type === 'Ground' && move.category !== 'Status'
) bp /= 4;
if (
this.enemy &&
toID(this.enemy) === 'shedinja'
&& move.category !== 'Status' &&
tools.getEffectiveness(move.type, 'shedinja') < 1
) return 0;
if (toID(move.name) === 'stealthrock' && !this.setHazards.sr) {
bp += this.enemyTeam.length * 20;
}
if (toID(move.name) === 'spikes' && this.setHazards.spikes < 3) {
bp += this.enemyTeam.length * (3 - (this.setHazards.spikes || 0)) * 10;
}
const hasStab = data.pokedex[toID(mon.details.split(',')[0])].types.includes(move.type) && move.category !== 'Status';
bp *= hasStab ? mon.ability === 'adaptability' ? 2 : 1.5 : 1;
if (this.enemy && move.category !== 'Status') {
bp *= tools.getEffectiveness(move.type, this.enemy);
}
return bp;
}
firstPick () {
if (!this.enemyTeam.length) return console.log('No team detected.');
this.started = true;
switch (this.ai) {
case 0: return this.getIndex(this.side.pokemon.random().ident) + 1;
case 1: case 2: {
const out = {};
this.side.pokemon.forEach(mon => {
out[mon.ident] = mon.moves
.filter(move => data.moves[move.replace(/\d/g, '')].category !== 'Status')
.map(move => data.moves[move.replace(/\d/g, '')].type)
.map(type => this.enemyTeam.map(foe => tools.getEffectiveness(type, foe)).reduce((a, b) => a + b))
.reduce((a, b) => a > b ? a : b, 0);
});
const pick = this.random(out);
return this.getIndex(pick) + 1;
}
default: return null;
}
}
setEnemyData () {
this.enemyData = {
boosts: {
atk: 0,
def: 0,
spa: 0,
spd: 0,
spe: 0
},
ability: null,
item: null
};
return;
}
setActiveBoosts () {
this.selfBoosts = {
atk: 0,
def: 0,
spa: 0,
spd: 0,
spe: 0
};
return;
}
switchPick (forced) {
if (!this.enemy) {
if (this.ai === 0) {
return this.side.pokemon
.map((blank, i) => i + 1)
.filter(i => this.side.pokemon[i - 1].condition.includes('/') && !this.side.pokemon[i - 1].active)
.random();
} else {
return this.side.pokemon
.filter(mon => mon.condition.includes('/') && !mon.active)
.random().ident
.split(': ')
.slice(1)
.join(': ');
}
}
switch (this.ai) {
case 0: {
if (forced) {
return this.side.pokemon.map((blank, i) => i + 1)
.filter(i => this.side.pokemon[i - 1].condition.includes('/') && !this.side.pokemon[i - 1].active)
.random();
}
if (!forced && Math.random() > 0.1 || this.noSwitch) return false;
const opts = this.side.pokemon
.map((_, i) => i + 1)
.filter(i => this.side.pokemon[i - 1].condition.includes('/') && !this.side.pokemon[i - 1].active);
if (opts && opts.length) return opts.random();
else return false;
}
case 1: {
if (
this.active[0] && !forced &&
this.active[0].moves.filter(move => {
return (move.hasOwnProperty('pp') ? move.pp : true) &&
data.moves[move.id].category !== 'Status' &&
tools.getEffectiveness(data.moves[move.id].type, this.enemy) > 1;
}).length
) return false;
const out = {};
this.side.pokemon.filter(mon => {
return mon.condition.includes('/') && (!forced || !mon.active);
}).forEach(mon => {
out[mon.ident] = mon.moves
.filter(move => data.moves[toID(move)] && data.moves[toID(move)].category !== 'Status')
.map(move => data.moves[toID(move)].type)
.map(type => tools.getEffectiveness(type, this.enemy))
.reduce((a, b) => a > b ? a : b, 0) * (mon.active ? forced ? 0 : 10 : 1);
});
const pick = this.random(out);
if (!pick) return false;
if (this.getMon(pick).active && !forced) return false;
return pick.split(': ').slice(1).join(': ');
}
case 2: {
const out = {};
this.side.pokemon.filter(mon => mon.condition.includes('/') && !mon.active).forEach(mon => {
out[mon.ident] = mon.moves.map((m, i, ms) => this.moveWt(m, mon, ms) ** 4).reduce((a, b) => a > b ? a : b, 0);
});
// console.log(1, out);
if (this.getActive()) {
out[this.getActive().ident] = this.active[0].moves
.filter(move => !move.disabled && (move.hasOwnProperty('pp') ? move.pp : true))
.map((move, i, moves) => this.moveWt(move.move, this.getActive(), moves.map(v => v.move)) ** 4)
.reduce((a, b) => a > b ? a : b, 0) * 10;
}
if (this.sideHazards.sr) {
this.side.pokemon.filter(mon => {
return mon.condition.includes('/') && !mon.active;
}).forEach(mon => {
out[mon.ident] /= 1.1 + tools.getEffectiveness('rock', mon.ident.split(': ').slice(1).join(': '));
});
}
if (this.enemy) {
this.side.pokemon.filter(mon => {
return mon.condition.includes('/') && !mon.active;
}).forEach(mon => {
out[mon.ident] /= 1.1 + tools.getEffectiveness(this.enemy, mon.ident.split(': ').slice(1).join(': ')) ** 2;
});
}
if (forced) delete out[this.getActive().ident];
const pick = this.random(out);
if (this.getMon(pick).active) return null;
return pick.split(': ').slice(1).join(': ');
}
default: return null;
}
}
pickMove () {
if (!this.enemy || !this.active[0]) return;
switch (this.ai) {
case 0: {
return this.active[0].moves.filter(move => {
return (move.hasOwnProperty('pp') ? move.pp : true) && !move.disabled;
}).random().move;
}
case 1: {
const out = {};
if (!this.active[0].moves.filter(move => (move.hasOwnProperty('pp') ? move.pp : true) && !move.disabled).length) {
return 'Struggle';
}
this.active[0].moves
.filter(m => {
return (m.hasOwnProperty('pp') ? m.pp : true) && !m.disabled && data.moves[m.id].category !== 'Status';
}).forEach(move => {
const eff = tools.getEffectiveness(data.moves[move.id].type, this.enemy);
const base = eff * (data.moves[move.id].basePower || 60);
const dexMon = data.pokedex[toID(this.getActive().details.split(', ')[0])];
const isStab = dexMon.types.includes(data.moves[move.id].type);
const stab = isStab ? this.getActive().ability === 'adaptability' ? 2 : 1.5 : 1;
out[move.move] = (base * stab) ** 4;
});
if (!Object.keys(out).length) {
return this.active[0].moves.filter(move => {
return (move.hasOwnProperty('pp') ? move.pp : true) && !move.disabled;
}).random().move;
}
return this.random(out);
}
case 2: {
const moves = this.active[0].moves
.filter(move => (move.hasOwnProperty('pp') ? move.pp : true) && !move.disabled)
.map(move => move.move);
const out = {};
moves.forEach(move => out[move] = this.moveWt(move, this.getActive(), moves) ** 4);
// Bot.say(this.room, '!code ' + JSON.stringify(out, null, 2));
return this.random(out);
}
default: return null;
}
}
}
exports.AI = {
games: {},
newGame: function (room, side) {
if (!this.games[room]) this.games[room] = new game(room, side);
return this.games[room];
}
};
<file_sep>/handlers/autores.js
/* eslint-disable max-len */
/* eslint-disable no-unreachable */
exports.check = function (message, by, room) {
const userRank = by.match(/^\W/) || ' ';
by = by.replace(/^\W/, '');
message = message.replace(/\[\[\]\]/g, '');
if (toID(message.slice(0, -1)) === toID(Bot.status.nickName) && message.substr(-1) === '?') return Bot.pm(by, `Hi, I'm ${Bot.status.nickName}! I'm a Bot by ${config.owner}. My prefix is \`\`${prefix}\`\`. For more information, use \`\`${prefix}help\`\`.`);
if (toID(message) === toID(Bot.status.nickName + 'forhelp')) return Bot.pm(by, '-_-, very funny');
switch (room) {
case 'scavengers': {
if (/^\*\*(?:(?:SHUT UP|FUCK(?: Y?OU?)?)(?: PARTMAN)? ){3,}/.test(message)) Bot.say(room, `/roomban ${by}, No you`);
if (userRank === ' ' && (message.match(/\*\*[^*]*\*\*/g) || []).reduce((a, b) => a + b, '').length > 40) return client.channels.cache.get('808961324851396608').send(`Suspicious message: \n${by}: ${message}`);
break;
}
case 'redacted': {
if (/kicks.*snom/.test(message)) return Bot.say(room, '/me kicks ' + by);
if (new RegExp(`(?:with|alongside|with.*from|help.*of) ${Bot.status.nickName}$`, 'i').test(message)) break;
if (toID(message) === 'kden' && toID(by) === 'joltofjustice') return Bot.say(room, 'Kden.');
// if (toID(by) === 'hydro' && /^(?:|[^\/].* )i(?:'?| a)m .{2,}/i.test(message)) return Bot.pm(by, `Hi, ${message.split(/i(?:'| a)m /i)[1].replace(/[^a-zA-Z0-9]*?$/, '')}! I'm ${Bot.status.nickName}!`);
break;
if (/^\/me flee/.test(message)) return Bot.say(room, `/me catches ${by}`);
if (/^\/me runs/.test(message)) return Bot.say(room, `/me chases ${by} down`);
if (/^\/me hides/.test(message) && !message.toLowerCase().includes(Bot.status.nickName.toLowerCase())) return Bot.say(room, `/me chains ${by}`);
if (/^right/.test(message) && toID(by) !== 'partman') break;
// if (new RegExp(`, ?${Bot.status.nickName}\.?$`, 'i').test(message) && !/\. /.test(message)) return Bot.say(room, message.replace(new RegExp(`, ?${Bot.status.nickName}\.?$`, 'i'), '') + ', ' + by + '.');
if (new RegExp(`^/me .*${Bot.status.nickName}$`, 'i').test(message) && toID(message).split(toID(Bot.status.nickName)).length === 2) return Bot.say(room, message.replace(new RegExp(`${Bot.status.nickName}`, 'i'), by));
if (new RegExp(`^${Bot.status.nickName} is a `, 'i').test(message)) return Bot.say(room, 'N-no, you.');
if (Math.random() < 0.1 && /^(?:|[^\/].* )i(?:'?| a)m .{2,}/i.test(message)) return Bot.say(room, `Hi, ${message.split(/i(?:'| a)m /i)[1].replace(/[^a-zA-Z0-9]*?$/, '')}! I'm ${Bot.status.nickName}!`);
break;
}
case 'boardgames': {
if (/^\/log \(.*? added a new quote: "/.test(message)) Bot.roomReply(room, by, 'U-umm senpai could you also please add the quote to me using ,q a >///<');
if (/^\*\*(?:(?:SHUT UP|FUCK(?: Y?OU?)?)(?: PARTMAN)? ){3,}/.test(message)) Bot.say(room, `/roomban ${by}, No you`);
if ((Math.random() < 0.1 || toID(by) === "mengy") && /^(?:|[^\/].* )i(?:'?| a)m .{2,}/i.test(message)) return Bot.say(room, `Hi, ${message.split(/i(?:'?| a)m /i)[1].replace(/[^a-zA-Z0-9]*?$/, '')}! I'm ${Bot.status.nickName}!`);
break;
}
case 'hplauction': {
if (/has bought .* for \d+[50]00!/.test(message) && toID(by) === 'scrappie') client.channels.cache.get('855537911566303262').send(message);
break;
}
case 'healthfitness': {
if (message.startsWith('/uhtml')) break;
const rgxs = [
{ regex: /\b(?:(?:(\d{1,5}(?:[\.,]\d{1,5})?)(?: ?f(?:eet|oot|t)|'))(?:(?:(?: and| &|,)?) ?((?:\d{1,5}(?:[\.,]\d{1,5})?))(?: ?in(?:che?)?(?:s)?|"|))?|((?:\d{1,5}(?:[\.,]\d{1,5})?))(?: ?in(?:che?)?(?:s)?|"))(?:\b| |$)/gi, type: ['ft', 'in', 'in'], si: 'IMP', unit: 'L' },
{ regex: /\b(\d{1,5}(?:[\.,]\d{1,5})?) ?mi(?:les?)?\b/gi, type: ['mi'], si: 'IMP', unit: 'l' },
{ regex: /\b(\d{1,5}(?:[\.,]\d{1,5})?) ?k(?:ilo)?m(?:et(?:er|re))?s?\b/gi, type: ['km'], si: 'SI', unit: 'l' },
{ regex: /\b(\d{1,5}(?:[\.,]\d{1,5})?) ?m(?:et(?:er|re)s?)?\b/gi, type: ['m'], si: 'SI', unit: 'L' },
{ regex: /\b(\d{1,5}(?:[\.,]\d{1,5})?) ?c(?:enti)?m(?:et(?:er|re))?s?\b/gi, type: ['cm'], si: 'SI', unit: 'L' },
{ regex: /\b(\d{1,5}(?:[\.,]\d{1,5})?) ?(?:lb|pound)s?\b/gi, type: ['lb'], si: 'IMP', unit: 'M' },
{ regex: /\b(\d{1,5}(?:[\.,]\d{1,5})?) ?k(?:ilo)?g(?:ram)?s?\b/gi, type: ['kg'], si: 'SI', unit: 'M' }
];
const finals = [];
rgxs.forEach(rgx => {
const matches = Array.from(message.matchAll(rgx.regex));
if (!matches.length) return;
const maps = {
IMP: {
L: { ft: 30.48, in: 2.54 },
l: { mi: 1.609 },
M: { lb: 0.4536 }
},
SI: {
L: { m: 39.37, cm: 0.3937 },
l: { km: 0.621 },
M: { kg: 2.204 }
}
};
const outs = {
IMP: [[100, 'm'], [1, 'cm']],
SI: [[12, 'ft'], [1, 'in']]
};
const mapped = matches.map(match => {
return match
.slice(1)
.map(num => Number((num || '0').replaceAll(',', '.')) || 0)
.reduce((a, b, i) => a + b * maps[rgx.si][rgx.unit][rgx.type[i]], 0);
});
if (!mapped.length) return;
finals.push(...mapped.map((num, i) => {
if (rgx.unit === 'l') return {
val: tools.escapeHTML(`${matches[i][0]} = ${~~(1000 * num) / 1000} ${{ IMP: 'km', SI: 'mi' }[rgx.si]}`),
index: matches[i].index
};
if (rgx.unit === 'M') return {
val: tools.escapeHTML(`${matches[i][0]} = ${~~(1000 * num) / 1000} ${{ IMP: 'kg', SI: 'lb' }[rgx.si]}`),
index: matches[i].index
};
const slice = outs[rgx.si];
const calced = [];
while (slice.length > 1) {
const amt = ~~(num / slice[0][0]);
num %= slice[0][0];
if (amt) calced.push(`${amt} ${slice[0][1]}`);
slice.shift();
}
calced.push(`${~~(1000 * num) / 1000} ${slice[0][1]}`);
return { val: tools.escapeHTML(matches[i][0] + ' = ' + calced.join(', ')), index: matches[i].index };
}));
});
if (!finals.length) break;
Bot.say(room, `/adduhtml CONVERSION${Date.now()}, ${finals.sort((a, b) => a.index - b.index).map(term => `<small>${term.val}</small>`).join(' | ')}`);
break;
}
case 'pokemongo': {
if (/^\/log \(.*? added a new quote: "/.test(message)) Bot.roomReply(room, by, 'U-umm senpai could you also please add the quote to me using ,q a >///<');
break;
}
case 'pokemonunite': {
if (tools.hasPermission(by, 'alpha', room) && message === ',chess n') return Bot.say(room, `!htmlbox <marquee><h1>YOU WERE WARNED NOT TO DO THIS</h1></marquee>`);
break;
}
case 'trickhouse': {
if (toID(by) === 'officerjenny') {
return; // Disabled since we're using `,trick` on Discord instead for now
const match = message.match(/^\/announce \*\*(.*?)\*\* just completed the \*\*(.*?)\*\* challenge! Congratulations!$/);
if (match) {
// Bot.say(room, match.slice(1, 3).join(' | '));
const [, challenger, challenge] = match;
const difficulty = Bot.DB('trickhouse').get(toID(challenge));
const html = `<form data-submitsend="/w ${Bot.status.nickName},${prefix}trickhouse {challenger}, {difficulty}, {replay}">Challenge detected for user <input type="text" value="${challenger}" name="challenger"/> of difficulty <select name="difficulty"><option name="difficulty" value="1"${difficulty === 1 ? 'selected' : ''}>Easy</option><option name="difficulty" value="2"${difficulty === 2 ? 'selected' : ''}>Medium</option><option name="difficulty" value="3"${difficulty === 3 ? 'selected' : ''}>Hard</option></select> (the ${challenge} Challenge). Challenge replay: <input type="text" placeholder="Paste replay link here" name="replay"/><br/><button>Submit!</button></form>`;
Bot.say(room, `/addrankuhtml %, trickhouse-${toID(challenge)}-${toID(challenger)}-${Date.now()}, ${html}`);
}
}
}
}
};
<file_sep>/data/VR/TC7/dragon.js
exports.dragon = {
sp: ["Latias", "Haxorus"],
s: ["Garchomp", "Tyrunt"],
sm: ["Naganadel"],
ap: ["Zygarde"],
a: ["Goodra"],
am: ["Latias-Mega"],
bp: ["Latios", "Salamence"],
b: ["Kommo-o"],
bm: ["Latios-Mega"],
cp: ["Turtonator"],
c: ["Guzzlord"],
cm: ["Noivern"],
d: [],
e: [],
unt: ["Druddigon", "Drampa", ",Tyrantrum", "Hydreigon,"],
bans: ["Altarianite", "Dragonite", "Kyurem"]
};
<file_sep>/commands/botdevelopment/cactus.js
module.exports = {
cooldown: 1,
help: `Form link.`,
permissions: 'none',
commandFunction: function (Bot, room, time, by, args, client) {
const hexes = args.join('').split(',').map(toID);
const L = hexes.length;
const board = Array.from({ length: L }).map((r, i) => Array.from({ length: L }).map((_, num) => num + i * (i + 1) / 2));
// eslint-disable-next-line max-len
Bot.say(room, `!htmlbox ${board.map(row => row.map(i => `<span style="color:#${hexes[i % L]};background-color:black;border:0.5px solid white;display:inline-block;height:25px;width:25px;line-height:25px;text-align:center;font-family:Verdana;">3</span>`).join('')).join('<br/>')}`);
}
};
<file_sep>/discord/pick.js
module.exports = {
help: `Picks stuff.`,
pm: true,
commandFunction: function (args, message, Bot) {
const cargs = args.join(' ').split(/\s*,\s*/);
return message.channel.send(`I randomly picked: ${cargs.random().replace(/@everyone/g, '@ everyone')}`);
}
};
<file_sep>/commands/hindi/tourpoll.js
module.exports = {
cooldown: 1000,
help: `Room ke tour polls. Syntax: \`\`${prefix}tourpoll (time in words / 'hour' / 'start' / 'cancel' / 'status')\`\``,
permissions: 'beta',
commandFunction: function (Bot, room, _time, by, args, client) {
const param = toID(args.join(''));
if (['end', 'stop', 'start'].includes(param)) {
if (!Bot.rooms[room].tourpoll) return Bot.say(room, `Koi tour poll chalu nahi hai!`);
if (!tools.runEarly(Bot.rooms[room].tourpoll.timer)) Bot.say(room, `Error occurred`);
return;
}
if (['cancel', 'delete'].includes(param)) {
if (!Bot.rooms[room].tourpoll) return Bot.say(room, `Koi tour poll chalu nahi hai!`);
clearInterval(Bot.rooms[room].tourpoll.timer);
delete Bot.rooms[room].tourpoll;
Bot.say(room, `Tour poll cancel hua hai!`);
return;
}
if (['status', 'view', 'current'].includes(param)) {
if (!Bot.rooms[room].tourpoll) return Bot.say(room, `Koi tour poll chalu nahi hai!`);
Bot.say(room, `/adduhtml TOURPOLL, ${Bot.rooms[room].tourpoll.html}`);
const timeLeft = tools.toHumanTime(Bot.rooms[room].tourpoll.timer._endTime - Date.now());
Bot.say(room, `Tour poll mei ${timeLeft.replace(' and ', ' aur ')} bache hai.`);
return;
}
if (Bot.rooms[room].poll) return Bot.pm(by, `A poll is already in progress!`);
let time;
if (['hour', 'onthehour', 'atthehour', 'oth', 'ath'].includes(param)) {
const date = new Date();
time = (60 - (30 + date.getMinutes()) % 60) * 60 * 1000;
time -= date.getSeconds() * 1000;
} else time = tools.fromHumanTime(param);
if (!time) return Bot.pm(by, `Invalid time specified!`);
const DB = require('origindb')('data/TOURS');
const obj = DB('hindi').object();
const opts = new Set();
while (opts.size < 4) opts.add(tools.random(obj));
Bot.rooms[room].tourpoll = {
votes: {},
options: opts
};
Bot.rooms[room].tourpoll.timer = setTimeout(async () => {
const poll = Bot.rooms[room].tourpoll;
if (!poll) return;
const OMs = {
'[Gen 9] Mayhem Random Battle': {
// eslint-disable-next-line max-len
code: '[Gen 9] Random Battle @@@ Team Preview, Max Teamsize=24, Picked Teamsize=6, [Gen 9] Shared Power, [Gen 9] Camomons, Scalemons Mod, Inverse Mod',
// eslint-disable-next-line max-len
note: 'Iss tour mei bahut saare effects active honge - Scalemons, Inverse, Shared Power, aur Camomons - 24 mei se 6 chunke khelo!'
},
'[Gen 8] Shared Power Random Battle': {
// eslint-disable-next-line max-len
code: '[Gen 8] Random Battle @@@ Team Preview, Max Teamsize=24, Picked Teamsize=6, [Gen 8] Shared Power',
// eslint-disable-next-line max-len
note: 'Iss tour mei Shared Power active hoga, aur aapko 24 Pokemon mei se 6 chunne honge!'
},
'[Gen 8] Mayhem Random Battle': {
// eslint-disable-next-line max-len
code: '[Gen 8] Random Battle @@@ Team Preview, Max Teamsize=24, Picked Teamsize=6, [Gen 8] Shared Power, [Gen 8] Camomons, Scalemons Mod, Inverse Mod',
// eslint-disable-next-line max-len
note: 'Iss tour mei bahut saare effects active honge - Scalemons, Inverse, Shared Power, aur Camomons - 24 mei se 6 chunke khelo!'
}
};
/* const cache = {};
async function altsOf (user) {
if (cache[user]) return cache[user];
const alts = await tools.getAlts(user, 0);
cache[user] = alts;
return alts;
}
const cloned = tools.deepClone(poll.votes);
const alters = [];
for (u of Object.keys(cloned)) {
const alts = await altsOf(u);
if (alts) for (alt of alts) {
if (cloned[alt] && alt !== u) {
// GOTTEM'
const whitelist = ['abhighostkiller|yash0987'];
if (whitelist.includes([alt, u].sort().join('|'))) continue;
alters.push({ alt, u });
delete poll.votes[alt];
}
}
}
if (alters.length) {
const groups = [];
alters.forEach(({ alt, u }) => {
const group = groups.find(group => group.has(alt) || group.has(u));
if (group) {
group.add(alt);
group.add(u);
} else groups.push(new Set([alt, u]));
});
const grouped = groups.map(group => [...group].sort()).sort((a, b) => b.length - a.length);
grouped.forEach(group => {
Bot.say(room, `/modnote TOURPOLL ALTS: ${tools.listify(group.map(n => `[${n.toUpperCase()}]`))}`);
});
*/
// eslint-disable-next-line max-len
// client.channels.cache.get('901113072226287686').send(`Tourpoll flagged alts: ${grouped.map(group => tools.listify(group.map(n => `[${n.toUpperCase()}]`))).join('\n')}`);
// }
const opts = poll.options, votes = {};
opts.forEach(opt => votes[opt] = 0);
Object.values(poll.votes).forEach(vote => votes[vote]++);
const seq = Object.values(votes).sort((a, b) => b - a), max = seq[0];
let result = Object.keys(votes).filter(vote => votes[vote] === max).random();
let note = false, oldResult;
if (OMs[result]) {
note = OMs[result].note;
oldResult = result;
result = OMs[result].code;
}
const voteAmt = Object.values(votes).reduce((a, b) => a + b);
const [res, rules] = result.split('@@@').map(t => t.trim());
// eslint-disable-next-line max-len
Bot.say(room, `/adduhtml TOURPOLL, <div class="infobox"><p style="margin: 2px 0 5px 0"><span style="border: 1px solid #6a6; color: #848; border-radius: 4px; padding: 0 3px"><i class="fa fa-bar-chart"></i> Poll khatm</span><strong style="font-size: 11pt"> Aap kaunsa format khelna chahoge?</strong></p>${Object.keys(votes).map(tier => `<div style="margin-top: 14px"><strong>${tier} (${Math.round(votes[tier] * 100 / voteAmt)}%)</strong>${tier === res ? ' ⭐' : ''}</div>`).join('')}</div>`);
let tourType = 'elimination';
if (res.endsWith(' 1v1')) tourType = 'elim,, 2';
Bot.say(room, `/tour create ${res}, ${tourType}`);
if (oldResult) Bot.say(room, `/tour name ${oldResult}`);
if (rules) Bot.say(room, `/tour rules ${rules}`);
if (note) Bot.say(room, `/wall ${note}`);
obj[res][0] = 0;
Object.keys(obj).forEach(tier => {
if (opts.has(tier)) return;
if (obj[tier][0] >= 7) return;
obj[tier][0] += obj[tier][1];
});
DB.save();
delete Bot.rooms[room].tourpoll;
}, time);
Bot.rooms[room].tourpoll.timer._endTime = Date.now() + time;
// eslint-disable-next-line max-len
Bot.rooms[room].tourpoll.html = `<div class="infobox"><p style="margin: 2px 0 5px 0"><span style="border: 1px solid #6a6; color: #848; border-radius: 4px; padding: 0 3px"><i class="fa fa-bar-chart"></i> Tour Poll</span><strong style="font-size: 11pt"> Aap kaunsa format khelna chahoge?</strong></p>${[...opts].map(tier => `<div style="margin-top: 5px"><button class="button" value="/botmsg ${Bot.status.nickName}, ${prefix}tourpoll vote ${room}, ${tier}" name="send"> <strong>${tier}</strong></button></div>`).join('')}</div>`;
Bot.say(room, `/adduhtml TOURPOLL,${Bot.rooms[room].tourpoll.html}`);
}
};
|
0c6e2c4a579518c35f93c1237b5e1250a8c08cd1
|
[
"JavaScript",
"Markdown"
] | 209
|
JavaScript
|
PartMan7/PartBot
|
01ee933fc7623c1e1590bbb7d592ebc39d6c7df0
|
77f29eb4f582acc71a32afc381f84e61eb417626
|
refs/heads/master
|
<repo_name>cocodrips/magazine-style-layout<file_sep>/brute_force_layout.py
from base import Base
from page_utils import PageUtils
import itertools
class BruteForceLayout(Base):
def layout(self, rect, page_set, is_grouping=False):
if is_grouping:
self.grouping()
<file_sep>/greedy_layout.py
# -*- coding: utf-8 -*-
from base import Base
from page_utils import PageUtils
from model.rect_type import rect_types
from model.rect import Rect
import copy
import math
MIN_WIDTH = 200
MIN_HEIGHT = 60
class GreedyLayout(Base):
def layout(self):
group_sets = PageUtils.grouping(self.page_set)
PageUtils.deform_priorities(group_sets, self.width * self.height, MIN_WIDTH, MIN_HEIGHT)
self._set_ideal_area(group_sets)
PageUtils.sort(group_sets, reverse=True, key=lambda x: (PageUtils.sum(x) / PageUtils.num(x)))
self._arrange(group_sets, Rect(0, 0, self.width, self.height))
def _set_ideal_area(self, page_sets):
priority_sum = PageUtils.sum(page_sets)
area = self.width * self.height
self._priority_ratio(page_sets, area, priority_sum)
def _priority_ratio(self, page_sets, area, priority_sum):
if not PageUtils.is_group(page_sets):
page_sets.ideal_area = page_sets.priority * area // priority_sum
else:
for page_set in page_sets:
self._priority_ratio(page_set, area, priority_sum)
def _arrange(self, page_sets, rect):
if not page_sets:
return
elif len(page_sets) < 3:
self._split(page_sets, rect)
else:
self._arrange_top_left(page_sets, rect)
def _split(self, page_sets, rect):
vertical_rects = self._split_page_sets_area(page_sets, rect, is_vertical=True, fix=False)
diff = 0
for i, vertical_rect in enumerate(vertical_rects):
ratio_type = page_sets[i].type if not PageUtils.is_group(page_sets[i]) else page_sets[i][0].type
diff += self._diff_ratio(vertical_rect, ratio_type)
min_diff = diff
is_vertical = True
horizontal_rects = self._split_page_sets_area(page_sets, rect, is_vertical=False, fix=False)
diff = 0
for i, horizontal_rect in enumerate(horizontal_rects):
ratio_type = page_sets[i].type if not PageUtils.is_group(page_sets[i]) else page_sets[i][0].type
diff += self._diff_ratio(horizontal_rect, ratio_type)
if diff < min_diff:
is_vertical = False
self._split_page_sets_area(page_sets, rect, is_vertical=is_vertical)
def _arrange_top_left(self, page_sets, rect):
tops = PageUtils.max(page_sets)
remaining_sets = PageUtils.new_sets(page_sets, tops)
length = len(tops)
optimal_tops_rect = None
optimal_sets = []
min_diff = 1000000000
ideal_area = PageUtils.ideal_sum(tops)
is_vertical = False
for rect_type in rect_types[tops[0].type]:
if rect_type.min_align > length:
continue
# vertical
diff, bottom_sets, top_rect = (
self._fix_top_left_rect(remaining_sets, rect, ideal_area, rect_type.ratio / length) )
if diff < min_diff:
min_diff = diff
optimal_tops_rect = top_rect
optimal_sets = bottom_sets
is_vertical = True
# horizontal
diff, bottom_sets, top_rect = (
self._fix_top_left_rect(remaining_sets, rect, ideal_area, rect_type.ratio * length) )
if diff < min_diff:
min_diff = diff
optimal_tops_rect = top_rect
optimal_sets = bottom_sets
is_vertical = False
width = (PageUtils.ideal_sum(tops) + PageUtils.ideal_sum(optimal_sets)) / rect.height
optimal_tops_rect.height = int(optimal_tops_rect.area / width)
optimal_tops_rect.width = width
bottom_sets_rect = self._bottom_rect(rect, optimal_tops_rect)
remaining_rect = copy.deepcopy(rect)
remaining_rect.x += width
remaining_rect.width -= width
for target in optimal_sets:
remaining_sets = PageUtils.new_sets(remaining_sets, target)
self._split(tops, optimal_tops_rect)
self._arrange(optimal_sets, bottom_sets_rect)
self._arrange(remaining_sets, remaining_rect)
def _fix_top_left_rect(self, remaining_sets, parent_rect, ideal_area, ratio):
"""
Calc top left temporary rect and return bottom area difference from optimum sets.
"""
top_rect = copy.deepcopy(parent_rect)
top_rect.height = int(math.sqrt(ideal_area / ratio))
top_rect.width = int(ratio * top_rect.height)
if parent_rect.height - top_rect.height < MIN_HEIGHT:
top_rect.height = parent_rect.height
top_rect.width = int(ideal_area / top_rect.height)
if parent_rect.width - top_rect.width < MIN_WIDTH:
top_rect.width = parent_rect.width
top_rect.height = int(ideal_area / top_rect.width)
bottom_rect = self._bottom_rect(parent_rect, top_rect)
diff, bottom_sets = self._diff_from_ideal_area(remaining_sets, bottom_rect)
return diff, bottom_sets, top_rect
def _diff_from_ideal_area(self, remaining_sets, bottom_rect):
"""
Difference from bottom area.
"""
bottom_sets = PageUtils.get_optimal_set(remaining_sets, bottom_rect)
closest_area = PageUtils.ideal_sum(bottom_sets)
return abs(bottom_rect.area - closest_area), bottom_sets
def _bottom_rect(self, parent_rect, top_rect):
"""
Calc bottom rect using parent_rect and top_rect.
"""
return Rect(parent_rect.x,
parent_rect.y + top_rect.height,
top_rect.width,
parent_rect.height - top_rect.height)
def _split_page_sets_area(self, page_sets, rect, is_vertical, fix=True):
"""
Split page_sets area.
if page_sets[i] is group, calc parents_rect and call _arrange(page_sets[i], parent_rect)
"""
width, height = rect.width, rect.height
page_sets_ideal_sum = PageUtils.ideal_sum(page_sets)
tmp_rects = []
if is_vertical:
y = rect.y
if self.is_equally(page_sets):
height = rect.height / len(page_sets)
for page in page_sets:
if not self.is_equally(page_sets):
height = int(rect.height * (PageUtils.ideal_sum(page) / float(page_sets_ideal_sum)))
page_rect = copy.deepcopy(rect)
page_rect.y = y
page_rect.height = height
y += height
if not fix:
tmp_rects.append(page_rect)
continue
if PageUtils.is_group(page):
self._arrange(page, page_rect)
else:
page.rect = page_rect
else:
x = rect.x
if self.is_equally(page_sets):
width = rect.width / len(page_sets)
for page in page_sets:
if not self.is_equally(page_sets):
width = int(rect.width * (PageUtils.ideal_sum(page) / float(page_sets_ideal_sum)))
page_rect = copy.deepcopy(rect)
page_rect.x = x
page_rect.width = width
x += width
if not fix:
tmp_rects.append(page_rect)
continue
if PageUtils.is_group(page):
self._arrange(page, page_rect)
else:
page.rect = page_rect
if not fix:
return tmp_rects
def is_equally(self, page_sets):
for page in page_sets:
if PageUtils.is_group(page):
return False
return True
def _diff_ratio(self, rect, rect_type):
"""
Difference between current size and ideal size.
"""
min_ratio = 100
for t in rect_types[rect_type]:
ratio = float(rect.width) / rect.height
if t.ratio < ratio:
min_ratio = min(min_ratio, float(ratio) / t.ratio)
else:
min_ratio = min(min_ratio, float(t.ratio) / ratio)
return min_ratio
<file_sep>/tests/page_utils_test.py
# -*- coding: utf-8 -*-
from page_utils import PageUtils as utils
from model.rect import Rect
import unittest
import page_generator
import os
class PageUtilsTest(unittest.TestCase):
def setUp(self):
self.path = os.path.dirname(os.path.abspath(__file__))
self.generator = page_generator.PageGenerator()
self.page_set = self.generator.generate_from_jsonfile(self.path + '/sample/sample1.json')
self.pure_page_set = self.generator.generate_from_jsonfile(self.path + '/sample/pure_sample0.json')
def testSum(self):
target = utils.sum(self.page_set)
self.assertEqual(target, 34)
def testIsGroup(self):
target = utils.is_group(self.page_set)
self.assertTrue(target)
def testNum(self):
target = utils.num(self.page_set)
self.assertEqual(target, 7)
def testMax(self):
target = utils.max(self.page_set)
self.assertEqual(target[0].priority, 7)
def testSort(self):
utils.sort(self.page_set)
self.assertEqual(self.page_set[0][0].priority, 1)
utils.sort(self.page_set, reverse=True)
self.assertEqual(self.page_set[0][0].priority, 9)
self.page_set[1][2].priority = 100
utils.sort(self.page_set, reverse=True, key=lambda p: utils.avg(p))
self.assertEqual(self.page_set[0][0].priority, 100)
def testNewSets(self):
new_sets = utils.new_sets(self.page_set, self.page_set[0][0])
target = utils.num(new_sets)
self.assertEqual(target, 6)
self.assertEqual(utils.num(self.page_set), 7)
new_sets[0][0].priority = 100
self.assertEqual(self.page_set[0][1].priority, 100)
def testIdealSum(self):
self.page_set[0][0].ideal_area = 100
self.page_set[0][1].ideal_area = 123
target = utils.ideal_sum(self.page_set)
self.assertEqual(target, 223)
def testGrouping(self):
target = utils.grouping(self.pure_page_set)
self.assertEqual(target[1][1].priority, 2)
def testGetOptimumSet(self):
for page in self.pure_page_set:
page.ideal_area = pow(page.priority * 100, 2)
target = utils.get_optimal_set(self.pure_page_set, Rect(0, 0, 500, 300))
self.assertEqual(target[0].priority, 4)
def testDeformPriorities(self):
self.assertEqual(self.pure_page_set[0].priority, 10)
utils.deform_priorities(self.pure_page_set, 800 * 600, 200, 60)
self.assertEqual(self.pure_page_set[0].priority, 8)
if __name__ == "__main__":
unittest.main()
<file_sep>/model/page.py
from rect import Rect
class Page:
def __init__(self, priority, string, name=None):
self.priority = priority
self.original_priority = priority
self.type = string
self.rect = Rect()
self.id = priority
self.ideal_area = 0
self.name = name
def __repr__(self):
return unicode("<Page priority:{0}({1})>".format(self.original_priority, self.ideal_area))
def __eq__(self, target):
if isinstance(target, Page):
return self.id == target.id
return False
<file_sep>/page_generator.py
import json
import model
import types
class PageGenerator():
def generate_from_jsonfile(self, filename):
dictionary = self.json_to_dict(filename)
return self.dict_to_page(dictionary)
def dict_to_page(self, dictionary):
if dictionary.get('size'):
return model.Page(dictionary.get('size'), dictionary.get('type'), dictionary.get('name'))
pages = []
for data in dictionary.get('children'):
pages.append(self.dict_to_page(data))
return pages
def json_to_dict(self, filename):
with open(filename, 'r') as f:
json_string = f.read()
d = json.loads(json_string)
return d
<file_sep>/page_utils.py
# -*- coding: utf-8 -*-
from model.rect_type import rect_types
import itertools
import math
import types
class PageUtils(object):
@classmethod
def is_group(cls, page_set):
return type(page_set) == types.ListType
@classmethod
def sum(cls, page_sets):
"""
Return:
(int) Sum of priority of whole of sets.
"""
if not cls.is_group(page_sets):
return page_sets.priority
return sum([cls.sum(page_set) for page_set in page_sets])
@classmethod
def num(cls, page_sets):
if not cls.is_group(page_sets):
return 1
return sum(cls.num(page_set) for page_set in page_sets)
@classmethod
def avg(cls, page_sets):
"""
Return:
(int) Sum of priority of whole of sets.
"""
return cls.sum(page_sets) // cls.num(page_sets)
@classmethod
def max(cls, page_sets):
"""
Return:
(Page) Get page having highest average of priority.
"""
if not cls.is_group(page_sets):
return page_sets
return max(page_sets, key=lambda p: float(cls.sum(p)) / cls.num(p))
@classmethod
def sort(cls, page_sets, reverse=False, key=None):
"""
Sort all pages by priority.
Return:
None
"""
if not key:
key = lambda p: cls.sum(p)
page_sets.sort(key=key,
reverse=reverse)
for page_set in page_sets:
if cls.is_group(page_set):
cls.sort(page_set, reverse=reverse, key=key)
@classmethod
def new_sets(cls, l, target):
return l if not cls.is_group(l) else [cls.new_sets(i, target) for i in l if i != target]
@classmethod
def ideal_sum(cls, page_sets):
if not cls.is_group(page_sets):
return page_sets.ideal_area
return sum([cls.ideal_sum(page_set) for page_set in page_sets])
@classmethod
def grouping(cls, page_sets, range=1.3):
"""
Grouping only aa list of page_sets
"""
page_sets = page_sets[:]
top = page_sets.pop(0)
groups = [[top]]
for rect_type in rect_types:
target_sets = [page_set for page_set in page_sets if page_set.type == rect_type]
PageUtils.sort(target_sets)
while target_sets:
base = target_sets.pop(0)
group = [base]
if target_sets and \
target_sets[0].priority <= int(math.ceil(base.priority * range)):
pair = target_sets.pop(0)
group.append(pair)
groups.append(group)
return groups
@classmethod
def get_optimal_set(cls, page_sets, rect):
# TODO:Refactoring
s = rect.width * rect.height
match = 0
optimum_set = None
for page_set in page_sets:
area_sum = PageUtils.ideal_sum(page_set)
if not optimum_set or abs(s - area_sum) < abs(s - match):
optimum_set = [page_set]
match = area_sum
for a, b in itertools.combinations(page_sets, 2):
area_sum = PageUtils.ideal_sum(a) + PageUtils.ideal_sum(b)
if abs(s - area_sum) < abs(s - match):
optimum_set = [a, b]
match = area_sum
return optimum_set
@classmethod
def deform_priorities(cls, page_sets, area, min_width, min_height):
priority_sum = cls.sum(page_sets)
area_min = min_width * min_height
x = float(area / area_min) / priority_sum
for page_set in page_sets:
if cls.is_group(page_set):
for page in page_set:
page.priority = math.ceil(math.log((math.ceil(x * page.priority)), 2))
else:
page_set.priority = math.ceil(math.log((math.ceil(x * page_set.priority)), 2))
<file_sep>/tests/brute_force_test.py
from brute_force_layout import BruteForceLayout
import unittest
import os
class BruteForceTest(unittest.TestCase):
def setUp(self):
self.path = os.path.dirname(os.path.abspath(__file__))
self.brute_force_layout = BruteForceLayout(self.path + '/sample/sample3.json')
if __name__ == "__main__":
unittest.main()
<file_sep>/base.py
import page_generator
# Rename
DEFAULT_WIDTH=800
DEFAULT_HEIGHT=600
class Base():
def __init__(self, filename, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT):
generator = page_generator.PageGenerator()
self.page_set = generator.generate_from_jsonfile(filename)
self.width = width
self.height = height
def layout(self):
pass
def new_sets(self, page_sets, target):
pass
<file_sep>/display.py
from Tkinter import Canvas, Tk
from page_utils import PageUtils
class Display():
def __init__(self, layout):
self.layout = layout
def show(self):
root = Tk()
canvas = Canvas(root, width=self.layout.width, height=self.layout.height)
self.layout.layout()
self.draw_page_sets(canvas, self.layout.page_set)
canvas.pack()
root.mainloop()
def draw_page_sets(self, canvas, page_sets):
if not PageUtils.is_group(page_sets):
self.draw_rectangle(canvas, page_sets)
else:
for page_set in page_sets:
self.draw_page_sets(canvas, page_set)
def draw_rectangle(self, canvas, page):
canvas.create_rectangle(page.rect.x, page.rect.y, page.rect.x + page.rect.width,
page.rect.y + page.rect.height,
outline="#222", width=4.0
)
canvas.create_text(page.rect.x + page.rect.width / 2, page.rect.y + 24,
text=str(page.original_priority), font=("Purisa", 42))
<file_sep>/model/__init__.py
from page import Page
from rect_type import rect_types
from rect import Rect
<file_sep>/tests/display_test.py
from greedy_layout import GreedyLayout
from display import Display
import unittest
import os
from model.rect_type import rect_types
from page_utils import PageUtils
class DisplayTest(unittest.TestCase):
def setUp(self):
filepath = os.path.dirname(os.path.abspath(__file__)) + '/sample/sample0.json'
layout = GreedyLayout(filepath, 800, 600)
self.display = Display(layout)
def testShow(self):
self.display.show()
def testSomeCase(self):
self.case1()
self.case2()
def case1(self):
filepath = os.path.dirname(os.path.abspath(__file__)) + '/sample/sample2.json'
layout = GreedyLayout(filepath, 1500, 1000)
self.display = Display(layout)
self.display.show()
self.score(layout)
def case2(self):
filepath = os.path.dirname(os.path.abspath(__file__)) + '/sample/sample5.json'
layout = GreedyLayout(filepath, 1500, 1000)
self.display = Display(layout)
self.display.show()
self.score(layout)
def score(self,layout):
diff_ratio = 0
min_ratio = 0
diff_scale = 0
for page in layout.page_set:
# print page.rect
r = float(page.rect.width) / page.rect.height
mini = 100
for t in rect_types[page.type]:
if r < t.ratio:
mini = min(mini, t.ratio / r)
else:
mini = min(mini, r / t.ratio)
min_ratio = max(min_ratio, mini * mini - 1)
diff_ratio += mini * mini - 1
print "diff ratio:", diff_ratio, "min:", min_ratio
print "diff scale", diff_scale
if __name__ == "__main__":
unittest.main()
<file_sep>/model/rect_type.py
class RectType:
def __init__(self, ratio, min_align=1):
self.ratio = ratio
self.min_align = min_align
rect_types = {
'image': [
RectType(0.9, 1),
RectType(1.6, 1),
RectType(3.0, 2),
RectType(3.8, 2)
],
'text': [
RectType(1.0, 1),
RectType(3.8, 1),
RectType(5, 1)
]
}<file_sep>/model/rect.py
# -*- coding: utf-8 -*-
IMAGE_RATIO = 1.3
class Rect:
x = 0
y = 0
width = 0
height = 0
def __init__(self, x=0, y=0, width=0, height=0):
self.x = x
self.y = y
self.width = width
self.height = height
@property
def ratio(self):
return self.width / float(self.height)
@property
def area(self):
return self.width * self.height
def vec4(self):
return (self.x, self.y, self.width, self.height)
def __repr__(self):
return unicode("<{}, {}, {}, {}>".format(self.x, self.y, self.width, self.height))
<file_sep>/tests/greedy_layout_test.py
from greedy_layout import GreedyLayout
from model.rect import Rect
from page_utils import PageUtils
import unittest
import os
class GreedyLayoutTest(unittest.TestCase):
def setUp(self):
self.path = os.path.dirname(os.path.abspath(__file__))
self.layout = GreedyLayout(self.path + '/sample/sample0.json', 800, 600)
def testSetIdealArea(self):
self.layout._set_ideal_area(self.layout.page_set)
self.assertEqual(self.layout.page_set[0].ideal_area, 138461)
if __name__ == "__main__":
unittest.main()
<file_sep>/tests/page_generator_test.py
import unittest
import page_generator
import os
class ParserTest(unittest.TestCase):
def setUp(self):
self.path = os.path.dirname(os.path.abspath(__file__))
self.generator = page_generator.PageGenerator()
def testParse(self):
page_set = self.generator.generate_from_jsonfile(self.path + '/sample/sample1.json')
self.assertEqual(len(page_set[1][2]), 2)
if __name__ == "__main__":
unittest.main()
|
6000e2c1f9f9a588745b87ae9650bd2c4cd7bbc5
|
[
"Python"
] | 15
|
Python
|
cocodrips/magazine-style-layout
|
f92a9214f8265685ca4dadb45bbc46c94f2aa7aa
|
312742c3c30c3e1385e618f7ad843040359dd0b4
|
refs/heads/master
|
<file_sep>const cheerio = require('cheerio');
const express = require('express');
const request = require('request-promise');
const fetch = require('node-fetch');
// test
let app = express();
app.use(express.static('public'));
app.use(express.json());
// Scrape stuff from codeforces.com and return the contests found
app.get('/api/codeforces/upcoming-contests', async (req, res) => {
let arrayOfContests = [];
const response = await request.get('https://codeforces.com/contests');
let $ = cheerio.load(response);
$(
'#pageContent > div.contestList > div.datatable > div:nth-child(6) > table > tbody > tr'
).each((index, element) => {
if (index === 0) return true; // Ignore the first row
let contest = {};
$('td', element).each((index, c) => {
if (index === 0) {
contest.name = $(c).text().replace(/\s+/g, ' ').trim();
} else if (index === 2) {
contest.dateTime = $(c).text().replace(/\s+/g, ' ').trim();
} else if (index === 3) {
contest.duration =
$(c).text().replace(/\s+/g, ' ').trim() +
'(days:hours:minutes)';
} else if (index === 4) {
contest.status = $(c).text().replace(/\s+/g, ' ').trim();
} else if (index === 5) {
contest.registerby =
$(c).text().replace(/\s+/g, ' ').trim() + '(hh:mm:ss/days)';
}
});
arrayOfContests.push(contest);
});
// console.log(arrayOfContests);
res.json(arrayOfContests);
});
let a = [],
b = [],
c = [],
d = [],
e = [],
f = [];
// Request and sort all problems from codeforces into divisions A<B<C<D<E<F
fetch('https://codeforces.com/api/problemset.problems')
.then((data) => data.json())
.then((data) => {
return data.result.problems;
})
.then((questions) => {
for (let i = 0; i < questions.length; i++) {
switch (questions[i].index) {
case 'A':
a.push(questions[i]);
break;
case 'B':
b.push(questions[i]);
break;
case 'C':
c.push(questions[i]);
break;
case 'D':
d.push(questions[i]);
break;
case 'E':
e.push(questions[i]);
break;
case 'F':
f.push(questions[i]);
break;
}
}
console.log(
'Finished requesting and grouping questions: ' + questions.length
);
});
// Get relevant question sets
app.get('/api/codeforces/problem-set/:index', (req, res) => {
let index = req.params.index;
switch (index) {
case 'a':
case 'A':
res.json(a);
break;
case 'b':
case 'B':
res.json(b);
break;
case 'c':
case 'C':
res.json(c);
break;
case 'd':
case 'D':
res.json(d);
break;
case 'e':
case 'E':
res.json(e);
break;
case 'f':
case 'F':
res.json(f);
break;
}
});
app.listen(process.env.PORT || 3000, () => {
console.log(`listening on port ${process.env.PORT}`);
});
<file_sep># Prereq
node.js, npm and git
# Usage Command
### 'git clone repo-url'
### npm install'
### npm start'
<file_sep>const apiBaseUrl = 'https://cp-dashboard-rohan.herokuapp.com/api/';
let username = 'rohank2205';
const default_playlist = 'https://open.spotify.com/embed/playlist/37i9dQZEVXbLRQDuF5jeBp'
if(!localStorage.getItem('spotify-uri')) {
localStorage.setItem("spotify-uri", default_playlist);
}
if(!localStorage.getItem('codeforces-username')) {
localStorage.setItem("codeforces-username", username);
}
const codeforcesEle = document.getElementById('codeforces');
username = localStorage.getItem('codeforces-username')
// Refresh on handle change
const displayHandleEle = document.getElementById('handle');
displayHandleEle.onchange = () => {
localStorage.setItem('codeforces-username', displayHandleEle.value)
location.reload()
}
// Set user info
fetch('https://codeforces.com/api/user.rating?handle=' + username)
.then((response) => response.json())
.then((data) => {
const displayHandleEle = document.getElementById('handle');
const currentRatingEle = document.getElementById('current-rating');
const contestDisplay = document.getElementById('contests-attended');
displayHandleEle.value = data.result[0].handle;
displayHandleEle.setAttribute(
'href',
'https://codeforces.com/profile/' + username
);
// set user rating
currentRatingEle.textContent =
'Current User Rating: ' +
data.result[data.result.length - 1].newRating;
// constest info
data.result = data.result.reverse();
for (let contest = 0; contest < data.result.length; contest++) {
let pTag = document.createElement('p');
pTag.textContent =
contest +
1 +
'. ' +
data.result[contest].contestName +
' Rank: ' +
data.result[contest].rank;
contestDisplay.appendChild(pTag);
}
})
.catch((error) => {
console.log('Error Occoured: ' + error);
});
// Set Upcoming cosntests list with time left in hrs
fetch(apiBaseUrl + 'codeforces/upcoming-contests')
.then((response) => response.json())
.then((data) => {
console.log(data);
const upcomingContestsEle =
document.getElementById('upcoming-contests');
const tTag = document.createElement('h3');
tTag.textContent = 'Upcoming Contests';
upcomingContestsEle.appendChild(tTag);
let i = 1;
for (let c = 0; c < data.length; c++) {
let contest = data[c];
let newContestDiv = document.createElement('p');
newContestDiv.textContent =
i++ +
'. Name: ' +
contest.name +
' Date time: ' +
contest.dateTime +
// ' Duration: ' +
// contest.duration +
// ' Status: ' +
// contest.status +
' Registration by/Status: ' +
contest.registerby;
upcomingContestsEle.appendChild(newContestDiv);
}
});
// Display problems to solve
// let timeOut = window.setTimeout(() => {
// setQuestions('A');
// }, 3000);
// window.clearTimeout(timeOut);
setQuestions('A');
function setQuestions(index) {
const questionsDiv = document.getElementById('questions');
const qWrap = document.createElement('div');
qWrap.setAttribute('id', 'qs');
// Remove previous questions
const pQs = document.getElementById('qs');
if (questionsDiv.lastChild === pQs) {
questionsDiv.removeChild(pQs);
}
fetch(apiBaseUrl + 'codeforces/problem-set/' + index)
.then((response) => response.json())
.then((data) => {
for (let d = 0; d < data.length; d++) {
let newDiv = document.createElement('div');
newDiv.setAttribute('class', 'question')
newDiv.innerHTML = `<p>${
d + 1
}. <a href="https://codeforces.com/contest/${
data[d].contestId
}/problem/${index}">${data[d].name}</a> (${data[d].points}) - ${
data[d].tags
} </p>`;
qWrap.appendChild(newDiv);
}
questionsDiv.appendChild(qWrap);
console.log('Loaded ' + data.length + ' questions!');
});
}
function getRandomQuestion() {
// Fetch questions with particular index/division
const questionsDiv = document.getElementsByClassName('question');
let randomIndex = Math.floor(Math.random() * questionsDiv.length)
const randomDiv = questionsDiv.item(randomIndex)
const randomQuestionDiv = document.getElementById('random-question')
// Remove any questions present before
while (randomQuestionDiv.firstChild) {
randomQuestionDiv.removeChild(randomQuestionDiv.firstChild);
}
randomQuestionDiv.innerHTML = randomDiv.innerHTML
}
const spotifyPlayerLink = document.getElementById('link')
const frame = document.createElement('div')
frame.innerHTML = '<iframe src="' + localStorage.getItem('spotify-uri') + '" width="100%" height="380" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>'
spotifyPlayerLink.setAttribute('value', localStorage.getItem('spotify-uri'))
document.getElementById('spotify-sidebar').appendChild(frame)
spotifyPlayerLink.onchange = () => {
localStorage.setItem('spotify-uri', spotifyPlayerLink.value)
location.reload()
}
|
4a25c40152a698fa513c6c2af908328e627c9def
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
RohanK22/cp-dashboard
|
579bd83347b459c7ee5560cf1b5cf4f672b68154
|
ce34d6a788bab1d0f48ce47804258f93c86e8d63
|
refs/heads/main
|
<repo_name>palagashviliniika/Book-Library<file_sep>/app.js
function Book(dasaxeleba,avtori,weli,Janri,gamomcemloba,fasi,url)
{
this.dasaxeleba = dasaxeleba;
this.avtori = avtori;
this.weli = weli;
this.Janri = Janri;
this.gamomcemloba = gamomcemloba;
this.fasi = fasi;
this.url = url;
}
var books = [];
books[0] = new Book("ვეფხისტყაოსანი"
,"შოთა რუსთაველი"
,"1978"
,"პოემა"
,"განათლება"
,"5,50"
,"Style/images/vefxistyaosani.jpg");
books[1] = new Book("სამოსელი პირველი",
"გურამ დოჩანაშვილი",
"2007",
"პროზა",
"აისი",
"5,0",
"Style/images/samoseli_resize.jpg");
books[2] = new Book("დიდოსტატის მარჯვენა"
,"კონსტანტინე გამსახურდია"
,"1968"
,"პროზა"
,"საქართველოს მაცნე"
,"13,5"
,"Style/images/didostati.jpg");
books[3] = new Book("იგი"
,"ჯემალ ქარჩხაძე"
,"1983"
,"პროზა"
,"საბჭოთა საქართველო"
,"1,65"
,"Style/images/igi.jpg");
books[4] = new Book("ლექსები"
,"მუხრან მაჭავარიანი"
,"1983"
,"პოეზია"
,"საბჭოთა საქართველო"
,"1.70"
,"Style/images/muxrani.jpg");
books[5] = new Book("თავისქალა არტისტული ყვავილებით"
,"გალაკტიონ ტაბიძე"
,"1982"
,"მოგზაურობა"
,"ნაკადული"
,"0.60"
,"Style/images/taviskala.jpg");
books[6] = new Book("კაცია ადამიანი?!"
,"ილია ჭავჭავაძე"
,"1977"
,"პროზა"
,"საბჭოთა საქართველო"
,"2.60"
,"Style/images/kaciaadamiani.jpg");
books[7] = new Book("ჯაყოს ხიზნები"
,"მიხეილ ჯავახიშვილი"
,"1991"
,"დიდაქტიკა"
,"განათლება"
,"27.00"
,"Style/images/jayo.png");
books[8] = new Book("სამი მუშკეტერი"
,"ალექსანდრე დიუმა"
,"1963"
,"პოეზია"
,"საბჭოთა საქართველო"
,"13.7"
,"Style/images/mushketeri.jpg");
function find_book() {
dasaxeleba = document.getElementById("dasaxeleba").value;
for( var j = 0; j < books.length; j++){
if( dasaxeleba == books[j].dasaxeleba ){
alert(books[j].avtori);
}
}
}
function add_book()
{
if(document.getElementById("r_dasaxeleba").value.length == 0)
{
alert("გთხოვთ შეავსოთ დასახელების ველი!");
}
else if(document.getElementById("autor").value.length == 0)
{
alert("გთხოვთ შეავსოთ ავტორის ველი!");
}
else if(document.getElementById("Janri").selectedIndex == 0)
{
alert("გთხოვთ მიუთითოთ ჟანრი!");
}
else{alert("შეკვეთა გადაცემულია, წიგნი მალე დაემატება, დარჩით სახლში!")}
}
<file_sep>/README.md
# Book-Library
Library WEBSITE
|
695c6ea485c376577c56a2e2f088b9625a40439c
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
palagashviliniika/Book-Library
|
16c34f87d6f03fdf15b55ab1555736039a22188f
|
7505b22e066e5676992e030f1781c909ca6497b2
|
refs/heads/master
|
<file_sep># Boball
<p>I made this little game for http://2015.js13kgames.com/</p>
<h3>Instructions:</h3>
<p>
Hi,<br>
Just use the mouse to play.<br>
Left click: place one white ball<br>
Right click: reverse the other ball<br>
The goal is to collide your white ball with the other who are in move..<br>
After some level, it's the line between your two balls who should be in collision..<br><br>
Have Fun :)
</p>
<file_sep>
var lastFrameTimeMs = 0;
var maxFPS = 120;
var delta = 0;
var timestep = 1000 / 120;
var fps = 120;
var framesThisSecond = 0;
var lastFpsUpdate = 0;
/**
* requestAnimationFrame
*/
window.requestAnimationFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
var elem = document.getElementById('canvasGame');
var ctx = elem.getContext('2d');
function random(min, max){
return (Math.random() * max | 0) + min;
}
function mouseClicked(e){
hasClicked = true;
if(!lostLevel && !win && !nextLevelState)
levels[currentLevel].eventMouseClicked(e);
}
var xMouse = 0;
var yMouse = 0;
function mouseMove(e){
xMouse = e.clientX;
yMouse = e.clientY;
}
var w = window,
e = document.documentElement,
g = document.getElementsByTagName('body')[0],
heightW = w.innerHeight|| e.clientHeight|| g.clientHeight;
var widthW = w.innerWidth|| e.clientWidth|| g.clientWidth;
ctx.canvas.width = widthW - 0;
ctx.canvas.height = heightW - 4;
var WIDTH = widthW;
var HEIGHT = heightW - 4;
var hasClicked = false;
var alpha = 0;
var audioHit = [];
audioHit.push(new Audio('sound/select.wav'));
audioHit.push(new Audio('sound/hit.wav'));
audioHit.push(new Audio('sound/hitSine.wav'));
var currentHit = 0;
function nextHitSong(){
if(currentHit + 1 == audioHit.length){
currentHit = -1;
}
audioHit[++currentHit].play();
}
var Point = function(x, y, color, dx, dy, speedX, speedY){
this.x = x;
this.y = y;
if(dx == undefined){
this.dx = parseInt(Math.random()*100)/100;
var inv = random(1, 2);
if(inv == 1){
this.dx *= -1;
}
}else{
this.dx = dx;
}
if(dy == undefined){
this.dy = parseInt(Math.random()*100)/100;
var inv = random(1, 2);
if(inv == 1){
this.dy *= -1;
}
}else{
this.dy = dy;
}
if(color == undefined){
this.color = randomColor();
}else{
this.color = color;
}
if(speedX == undefined){
this.speedX = random(2, 7);
}else{
this.speedX = speedX;
}
if(speedY == undefined){
this.speedY = random(2, 7);
}else{
this.speedY = speedY;
}
this.radius = 4;
this.inCollision = function(oPoint){
var distance = Math.sqrt((this.x - oPoint.x) *
(this.x - oPoint.x) +
(this.y - oPoint.y) *
(this.y - oPoint.y));
if(distance < this.radius + oPoint.radius){
return true;
}
return false;
}
}
var colors = ['#b543de', '#FF4B47', '#40E64F',
'#E0C93B', '#F58F39', '#39BAC5',
'#e63192'];
function randomColor(){
var rdm = Math.round(Math.random()*(colors.length-1));
return colors[rdm];
var color = '#';
for(var c = 0; c < 6; c++){
color += rdm;
rdm = Math.round(Math.random()*10);
}
return color;
}
var points = [];
var pointsTouched = [];
var mousePoints = [];
var currentLevel = -1;
var levels = [];
var flashBall = [];
function Level(goal, fctGeneration, logic, draw, fctMouseClicked){
this.goal = goal;
this.ballsPlaced = 0;
//methods
this.generation = fctGeneration;
this.logic = logic;
this.draw = draw;
this.eventMouseClicked = fctMouseClicked;
}
levels.push(new Level('Place one ball and capture 10 other with the first !',
function(){
for(var p = 0; p < 72; p++){
points.push(new Point(WIDTH/2,HEIGHT/2));
}
this.ready = false;
this.step = 0;
this.next = false;
},
function(){ //LOGIC
if(!this.ready){
if(hasClicked){
this.ready = true;
this.next = false;
}else{
return;
}
}else{
if(this.next){
if(this.step < 3){
this.ready = false;
this.step++;
}}
}
for(var p = 0; p < points.length; p++){
for(var m = 0; m < mousePoints.length; m++){
if(points[p].inCollision(mousePoints[m]) &&
pointsTouched.indexOf(points[p]) == -1){
points[p].color = 'white';
pointsTouched.push(points[p]);
var fb = new Point(points[p].x, points[p].y);
fb.color='white';
flashBall.push(fb);
nextHitSong();
if(this.step == 1 && this.ready){
this.next = true;
}
}
}
}
if(pointsTouched.length >= 10){
nextLevel();
}
},
function(){ //DRAW
if(!this.ready){
if(this.step == 0){
ctx.font = '23px serif';
ctx.fillStyle = 'white';
ctx.strokeStyle = "white";
ctx.lineWidth="10";
ctx.moveTo(200, 55);
ctx.lineTo(200, HEIGHT * 0.42);
ctx.moveTo(202, 55);
ctx.lineTo(150, 100);
ctx.moveTo(198, 55);
ctx.lineTo(250, 100);
ctx.stroke();
ctx.fillText('LEVEL INSTRUCTION', 100, HEIGHT * 0.42 + 25);
ctx.font = '42px serif';
ctx.shadowColor = randomColor();
ctx.shadowBlur="50";
ctx.fillText('Mouse Left: Put one ball', WIDTH/2 - 160, HEIGHT/2 - 20);
ctx.fillText('Mouse Right: Reverse the balls', WIDTH/2 - 185, HEIGHT/2 + 22);
ctx.fillText('Click to start.', WIDTH/2 - 50, HEIGHT/2 + 62);
}else if(this.step == 1){
mousePoints[0].radius = 20;
ctx.fillStyle = 'white';
ctx.shadowColor = randomColor();
ctx.shadowBlur="50";
ctx.font = '42px serif';
var y = HEIGHT/2 + (HEIGHT/2 - mousePoints[0].y);
ctx.fillText('This ball should be collided with one other..', WIDTH/2 - 200, y);
}else if(this.step == 2){
ctx.shadowColor = randomColor();
ctx.shadowBlur="50";
ctx.font = '42px serif';
ctx.fillStyle = 'white';
ctx.fillText('You see, one other ball was collided with the first', WIDTH/2 - 200, HEIGHT/2);
ctx.fillText('Continue to do that, to capture 10 balls !', WIDTH/2 - 200, HEIGHT/2 + 40);
}
}
},
function(e){ //MOUSECLIKED
if(!this.ready)
return;
if(e.button > 0){
for(var p = 0; p < points.length; p++){
points[p].speedX *= -1;
points[p].speedY *= -1;
}
}else{
mousePoints.push(new Point(e.clientX, e.clientY));
if(this.ready){
if(this.step == 0){
this.next = true;
}
}
}
}));
levels.push(new Level('3 balls this time !',
function(){
for(var p = 0; p < 15; p++){
points.push(new Point(random(1, WIDTH),random(1, HEIGHT)));
}this.ballsPlaced = 0;
},
function(){ //LOGIC
for(var p = 0; p < points.length; p++){
for(var m = 0; m < mousePoints.length; m++){
if(points[p].inCollision(mousePoints[m]) &&
pointsTouched.indexOf(points[p]) == -1){
points[p].color = 'white';
pointsTouched.push(points[p]);
nextHitSong();
var fb = new Point(points[p].x, points[p].y);
fb.color='white';
flashBall.push(fb);
}
}
}
if(this.ballsPlaced > 3 && mousePoints.length == 0){
lost();
return;
}
if(pointsTouched.length >= 3){
nextLevel();
}
},
function(){ //DRAW
},
function(e){ //MOUSECLIKED
if(e.button > 0){
for(var p = 0; p < points.length; p++){
points[p].speedX *= -1;
points[p].speedY *= -1;
}
}else{
if(this.ballsPlaced < 5){
mousePoints.push(new Point(e.clientX, e.clientY));
this.ballsPlaced++;
}}
}));
levels.push(new Level('Try 3 red balls !',
function(){
for(var p = 0; p < 10; p++){
var color = randomColor();
while(color == '#FF4B47'){
color = randomColor();
}
points.push(new Point(random(1, WIDTH),random(1, HEIGHT), color));
}
for(var p = points.length; p < 20; p++){
points.push(new Point(random(1, WIDTH),random(1, HEIGHT), '#FF4B47'));
}
this.ballsPlaced = 0;
this.ballsGoal = 3;
this.pointsMouseToLose = 3;
this.colorGoal = '#FF4B47';
},
function(){ //LOGIC
if(alpha < Math.PI){
alpha += 0.02;
animations['win'].logic();
if(alpha + 0.5 >= Math.PI){
alpha = Math.PI;
}
return;
}
for(var p = 0; p < points.length; p++){
for(var m = 0; m < mousePoints.length; m++){
if(points[p].inCollision(mousePoints[m]) &&
pointsTouched.indexOf(points[p]) == -1
&& points[p].color == this.colorGoal){
points[p].color = 'white';
pointsTouched.push(points[p]);
nextHitSong();
var fb = new Point(points[p].x, points[p].y);
fb.color=this.colorGoal;
flashBall.push(fb);
}
}
}
if(this.ballsPlaced >= this.pointsMouseToLose && mousePoints.length == 0){
lost();
return;
}
if(pointsTouched.length >= this.ballsGoal){
nextLevel();
}
},
function(){ //DRAW
if(alpha < Math.PI){
ctx.fillStyle = 'white';
ctx.shadowColor = 'white';
ctx.shadowBlur = animations['win'].step;
ctx.font = '42px serif';
ctx.fillText('LOADING', WIDTH/2 - 55, HEIGHT/2);
}
},
function(e){ //MOUSECLIKED
if(alpha < Math.PI)
return;
if(e.button > 0){
for(var p = 0; p < points.length; p++){
points[p].speedX *= -1;
points[p].speedY *= -1;
}
}else{
if(this.ballsPlaced < this.pointsMouseToLose+1){
mousePoints.push(new Point(e.clientX, e.clientY));
this.ballsPlaced++;
}
}
}));
levels.push(new Level('Try 3 green balls !',
function(){
for(var p = 0; p < 10; p++){
var color = randomColor();
while(color == '#40E64F'){
color = randomColor();
}
points.push(new Point(WIDTH/2,HEIGHT/2, color));
}
for(var p = points.length; p < 15; p++){
points.push(new Point(WIDTH/2,HEIGHT/2, '#40E64F'));
}
levels[currentLevel-1].ballsPlaced = 0;
levels[currentLevel-1].pointsMouseToLose = 2;
levels[currentLevel-1].colorGoal='#40E64F';
},
function(){ //LOGIC
levels[currentLevel-1].logic();
},
function(){ //DRAW
if(alpha < Math.PI){
ctx.fillStyle = 'white';
ctx.shadowColor = 'white';
ctx.shadowBlur = animations['win'].step;
ctx.font = '42px serif';
ctx.fillText('LOADING', WIDTH/2 - 55, HEIGHT/2);
}
},
function(e){ //MOUSECLIKED
if(alpha < Math.PI)
return;
if(e.button > 0){
for(var p = 0; p < points.length; p++){
points[p].speedX *= -1;
points[p].speedY *= -1;
}
}else{
if(levels[currentLevel-1].ballsPlaced < 3){
mousePoints.push(new Point(e.clientX, e.clientY));
levels[currentLevel-1].ballsPlaced++;
}
}
}));
levels.push(new Level('You have a new spell, place two balls to try. After that capture 5 balls with those line.',
function(){
for(var p = 0; p < 11; p++){
points.push(new Point(random(1, WIDTH),random(1, HEIGHT), randomColor(), undefined, undefined,
random(1, 4), random(1, 4)));
}
this.ballsPlaced = 0;
this.ballsGoal = 5;
this.pointsMouseToLose = 4;
},
function(){ //LOGIC
if(alpha < 2*Math.PI){
alpha += 0.1;
animations['win'].logic();
if(parseFloat(alpha) > 6.1){
alpha = 2*Math.PI;
}
return;
}
for(var p = 0; p < mousePoints.length; p++){
if(mousePoints[p].radius < 14){
mousePoints[p].radius+=0.1;
}
}
for(var m = 0; m < mousePoints.length; m++){
if(m % 2 != 0){
var a = (mousePoints[m-1].y - mousePoints[m].y) /
(mousePoints[m-1].x - mousePoints[m].x);
var b = -(a * mousePoints[m].x - mousePoints[m].y);
for(var p = 0; p < points.length; p++){
if(points[p].x >
((mousePoints[m].x < mousePoints[m-1].x) ?
mousePoints[m].x : mousePoints[m-1].x) &&
points[p].x <
((mousePoints[m].x > mousePoints[m-1].x) ?
mousePoints[m].x : mousePoints[m-1].x)){
var a1 = points[p].dy / points[p].dx;
var b1 = -(a1 * points[p].x - points[p].y);
var xColl = (b1 - b) / (a - a1);
var distance = Math.sqrt((points[p].x - xColl) *
(points[p].x - xColl) +
(points[p].y - (a*xColl+b)) *
(points[p].y - (a*xColl+b)));
if(distance < 10){
if(points[p].color == 'white' && !points[p].touched){
points[p].color = points[p].lastColor;
points[p].touched = true;
}else if(!points[p].touched && points[p].color != 'white'){
points[p].lastColor = points[p].color;
points[p].color = 'white';
points[p].touched = true;
nextHitSong();
var fb = new Point(xColl, a*xColl+b);
fb.color='white';
flashBall.push(fb);
pointsTouched.push(points[p]);
}
}else{
points[p].touched = false;
}
}
}
}
}
if(this.ballsPlaced > this.pointsMouseToLose && mousePoints.length == 0){
lost();
return;
}
if(pointsTouched.length >= this.ballsGoal){
nextLevel();
}
},
function(){ //DRAW
if(alpha < 2*Math.PI){
ctx.fillStyle = 'white';
ctx.shadowColor = 'white';
ctx.shadowBlur = animations['win'].step;
ctx.font = '42px serif';
ctx.fillText('LOADING', WIDTH/2 - 55, HEIGHT/2);
}else{
ctx.beginPath();
ctx.lineWidth = 4;
ctx.strokeStyle='white';
for(var m = 0; m < mousePoints.length; m++){
if(m % 2 != 0){
ctx.moveTo(mousePoints[m-1].x, mousePoints[m-1].y);
ctx.lineTo(mousePoints[m].x, mousePoints[m].y);
}
}
ctx.stroke();
}
},
function(e){ //MOUSECLIKED
if(alpha < 2*Math.PI)
return;
for(var p = 0; p < points.length; p++){
points[p].speedX *= -1;
points[p].speedY *= -1;
}
if(e.button == 0){
if(this.ballsPlaced < 6){
mousePoints.push(new Point(e.clientX, e.clientY));
this.ballsPlaced++;
}else{
lost();
hasClicked = false;
return;
}
}
}));
levels.push(new Level('Ok you have understand, now get 7 balls.',
function(){
for(var p = 0; p < 2; p++){
points.push(new Point(WIDTH/2 + p,HEIGHT/2, randomColor()));
}
levels[currentLevel-1].ballsPlaced = 0;
levels[currentLevel-1].ballsGoal = 7;
levels[currentLevel-1].pointsMouseToLose = 2;
},
function(){ //LOGIC
levels[currentLevel-1].logic();
},
function(){ //DRAW
if(alpha < 2*Math.PI){
ctx.fillStyle = 'white';
ctx.shadowColor = 'white';
ctx.shadowBlur = animations['win'].step;
ctx.font = '42px serif';
ctx.fillText('LOADING', WIDTH/2 - 55, HEIGHT/2);
}else{
ctx.beginPath();
ctx.lineWidth = 4;
ctx.strokeStyle='white';
for(var m = 0; m < mousePoints.length; m++){
if(m % 2 != 0){
ctx.moveTo(mousePoints[m-1].x, mousePoints[m-1].y);
ctx.lineTo(mousePoints[m].x, mousePoints[m].y);
}
}
ctx.stroke();
}
},
function(e){ //MOUSECLIKED
if(alpha < 2*Math.PI)
return;
for(var p = 0; p < points.length; p++){
points[p].speedX *= -1;
points[p].speedY *= -1;
}
if(e.button == 0){
if(this.ballsPlaced < 6){
mousePoints.push(new Point(e.clientX, e.clientY));
this.ballsPlaced++;
}else{
lost();
hasClicked = false;
return;
}
}
}));
function nextLevel(){
reset();
if(currentLevel == levels.length - 1){
win = true;
for(var p = 0; p < 120; p++){
points.push(new Point(random(1, WIDTH),random(1, HEIGHT)));
}
return;
}
if(currentLevel > -1){
nextLevelState=true;
}else{
levels[++currentLevel].generation();
}
}
function reset(){
points = [];
pointsTouched = [];
mousePoints = [];
flashBall = [];
}
var lostLevel = false;
var win = false;
function lost(){
lostLevel = true;
}
var messages = [];
//time in ms
//animation str
function Message(msg, x, y, time, animation){
this.msg = msg;
this.x = x;
this.y = y;
this.time = time;
this.animation = animation;
this.logic = function(){
if(this.startTime + this.time < Date.now()){
messages.splice(messages.indexOf(this), 1);
return;
}
if(this.animation != null)
animations[this.animation].logic();
}
this.draw = function(){
ctx.font = '30px serif';
ctx.fillText(this.msg, this.x, this.y);
}
this.startTime = Date.now();
messages.push(this);
}
function Animation(start, end, bearing){
this.start = start;
this.sens = 1;
this.step = start;
this.bearing = bearing;
this.end = end;
this.logic = function(){
if(this.step > this.end-1){
this.sens *= -1;
}else if(this.step < this.start){
this.sens *= -1;
}
this.step += (this.bearing * this.sens);
}
}
var animations = [];
animations['lost'] = new Animation(0, 16, 0.15);
animations['win'] = animations['lost'];
nextLevel();
function loop(timestamp){
// Throttle the frame rate.
if (timestamp < lastFrameTimeMs + (1000 / maxFPS)) {
requestAnimationFrame(loop);
return;
}
delta += timestamp - lastFrameTimeMs;
lastFrameTimeMs = timestamp;
if (timestamp > lastFpsUpdate + 1000) {
fps = 0.25 * framesThisSecond + 0.75 * fps;
lastFpsUpdate = timestamp;
framesThisSecond = 0;
}
framesThisSecond++;
var numUpdateSteps = 0;
while (delta >= timestep) {
update(timestep);
delta -= timestep;
if (++numUpdateSteps >= 240) {
panic();
break;
}
}
draw();
requestAnimationFrame(loop);
}
var nextLevelState = false;
function draw(){
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.save();
levels[currentLevel].draw();
ctx.fillStyle = 'white';
ctx.shadowBlur = 0;
ctx.font = '24px serif';
ctx.fillText(levels[currentLevel].goal, 22, 30);
ctx.fillText('balls captured: '+pointsTouched.length, 22, 60);
if(lostLevel){
ctx.fillStyle = 'white';
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowColor = 'white';
ctx.shadowBlur = animations['lost'].step;
ctx.font = '30px serif';
ctx.fillText('CLICK TO', WIDTH/2 - 42, HEIGHT/2-30);
ctx.font = '42px serif';
ctx.fillText('RETRY', WIDTH/2 - 42, HEIGHT/2);
}else if(win){
ctx.fillStyle = 'white';
ctx.font = '42px serif';
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowColor = 'white';
ctx.shadowBlur = animations['win'].step;
ctx.font = '72px serif';
ctx.fillText('Good Game !', WIDTH/2 - 200, HEIGHT/2);
}
if(nextLevelState){
ctx.fillStyle = 'white';
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowColor = 'white';
ctx.shadowBlur = animations['lost'].step;
ctx.font = '30px serif';
ctx.fillText('CLICK TO', WIDTH/2 - 42, HEIGHT/2-30);
ctx.font = '42px serif';
ctx.fillText('NEXT LEVEL', WIDTH/2 - 92, HEIGHT/2);
return;
}
ctx.translate(WIDTH/2,HEIGHT/2);
ctx.rotate(alpha);
ctx.translate(-WIDTH/2,-HEIGHT/2);
ctx.beginPath();
if(flashBall.length > 0){
ctx.fillStyle = flashBall[0].color;
ctx.globalAlpha = 0.4;
ctx.shadowBlur = 10;
ctx.shadowColor = flashBall[0].color;
}
for(var f = 0; f < flashBall.length; f++){
ctx.moveTo(flashBall[f].x, flashBall[f].y);
ctx.arc(flashBall[f].x, flashBall[f].y,
flashBall[f].radius, 0, 2 * Math.PI, false);
}ctx.fill();
ctx.globalAlpha = 1;
for(var p = 0; p < points.length; p++){
//ball
ctx.beginPath();
ctx.fillStyle = points[p].color;
ctx.shadowBlur = 16;
ctx.shadowColor = points[p].color;
ctx.arc(points[p].x, points[p].y, points[p].radius, 0, 2 * Math.PI, false);
ctx.fill();
}
ctx.beginPath();
ctx.fillStyle = 'white';
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = 20;
ctx.shadowColor = 'white';
for(var p = 0; p < mousePoints.length; p++){
ctx.moveTo(mousePoints[p].x, mousePoints[p].y);
ctx.arc(mousePoints[p].x, mousePoints[p].y,
mousePoints[p].radius, 0, 2 * Math.PI, false);
}
ctx.fill();
for(var m = 0; m < messages.length; m++){
messages[m].draw();
}
//draw mouse
ctx.beginPath();
ctx.fillStyle = 'white';
ctx.shadowBlur = 1;
ctx.lineWidth = 2;
ctx.arc(xMouse, yMouse, 11, 0, 2 * Math.PI, false);
ctx.fill();
ctx.beginPath();
ctx.arc(xMouse, yMouse, 8, 0, 2 * Math.PI, false);
ctx.stroke();
ctx.restore();
}
function panic() {
delta = 0;
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function update(){
for(var m = 0; m < messages.length; m++){
messages[m].logic();
}
for(var f = 0; f < flashBall.length; f++){
flashBall[f].radius += 0.8;
if(flashBall[f].radius > 70){
flashBall.splice(f, 1);
f--;
}
}
if(currentLevel < 4){
var mouseNeedDeleted = -1;
for(var p = 0; p < mousePoints.length; p++){
mousePoints[p].radius += 0.1;
if(mousePoints[p].radius >= 28){
mouseNeedDeleted = p;
}
}
if(mouseNeedDeleted >= 0){
mousePoints.splice(mouseNeedDeleted, 1);
}
}
for(var p = 0; p < points.length; p++){
if(points[p].x + points[p].speedX * points[p].dx >= WIDTH){
points[p].dx *= -1;
}
else if(points[p].x + points[p].speedX * points[p].dx <= 0){
points[p].dx *= -1;
}
if(points[p].y + points[p].speedY * points[p].dy >= HEIGHT){
points[p].dy *= -1;
}
else if(points[p].y + points[p].speedY * points[p].dy <= 0){
points[p].dy *= -1;
}
points[p].x += points[p].speedX * points[p].dx;
points[p].y += points[p].speedY * points[p].dy;
points[p].x = parseInt(points[p].x*100)/100;
points[p].y = parseInt(points[p].y*100)/100;
}
if(nextLevelState){
animations['win'].logic();
if(hasClicked){
levels[++currentLevel].generation();
nextLevelState = false;
}
return;
}
if(lostLevel){
animations['lost'].logic();
if(hasClicked){
reset();
levels[currentLevel].generation();
lostLevel = false;
}
}else if(!win){
levels[currentLevel].logic();
}else if(win){
animations['win'].logic();
}
hasClicked = false;
}
requestAnimationFrame(loop);
|
9c85e8d40de7e9fef196fd193d3d4331e090aa55
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Slayug/Boball
|
1c5b59ed54415c0bfc32fdd9e190100ba8e846be
|
02baaf1eef8dfb09aeba21b34209460562c362ee
|
refs/heads/master
|
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javafxapplication4;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.stage.Stage;
//import static javafxapplication4.JavaFXApplication4.matriuGuardies;
/**
*
* @author TOMAS
*/
public class JavaFXApplication4 extends Application {
public final int MAX_DADA = 10000;
public static int DIES = 5;// variable estàtica per poder accedir des de fora de la classe
public static int HORA = 20;// variable estàtica per poder accedir des de fora de la classe
public static int HORES_GUARDIA_DIA = 9; // variable estàtica per poder accedir des de fora de la classe (pati inclós). Número d'hores de guardia per dia
public int i = 0;
public int cont_h_grup = 0;
public int cont_h_profe = 0;
public int enteroDIA = 0;
public int enteroHORA = 0;
public String valor;
public String matriu[] = new String[MAX_DADA];
public static String grups[] = {"E1A", "E1B", "E1C", "E1D",
"E2A", "E2B", "E2C", "E2D",
"E3A", "E3B", "E3C", "E3D",
"E4A", "E4B", "E4C", "E4D",
"B1A", "B1B", "B2A", "B2B",
"CFA", "CFB", "CFC"};
/*
public static String profes[] = {"AN1", "AN2", "AN3", "AN4",
"ES1", "ES2", "ES3", "ES4",
"CA1", "CA2", "CA3", "CA4",
"MA1", "MA2", "MA3", "MA4",
"TE1", "TE2", "TE3", "TE4",
"HI1", "HI2", "HI3", "HI4"};
*/
//creo la matriu de guàrdies
public static int matriuGuardies[][][] = new int[DIES][HORA][];
// creo el hashmap per a recollir els profes
static Map<String, String> llista_profes = new HashMap<>();
public static String profes[];
public char SuperMatriu[][][];
public static char SuperMatriuProfes[][][];// variable estàtica per poder accedir des de fora de la classe
// Funció per treure els símbols "
public String sensecometes(String ambcometes) {
String sensecometes = "";
sensecometes = ambcometes.replace("\"", "");
return sensecometes;
}
@Override
public void start(Stage primaryStage) {
//*************************************************************************
System.out.println("Botó 3 premut: ");
System.out.println("Començo a importar");
//Get scanner instance
Scanner scanner;
try {
// compte amb la codificació, millor UTF-8
scanner = new Scanner(new File("dades/horaris.csv"));
//Set the delimiter used in file
scanner.useDelimiter(";");
//Get all tokens and store them in some data structure
//I am just printing them
while (scanner.hasNext()) {
valor = scanner.next();
if (i == 2 || i%8 == 2 ){
System.out.print("\n(" + i +") ");
System.out.print(sensecometes(valor) + " ");
String dada1 = Integer.toString(i);
if (!valor.equals("") && valor != null){
llista_profes.put(sensecometes(valor), sensecometes(valor));
}
}
// matriu[i] = sensecometes(valor);
i = i + 1;
}
//Do not forget to close the scanner
scanner.close();
System.out.println("\n Imprimim la mtriu profes amb els valors entrats ");
// Imprimimos el Map con un Iterador
//convertim el hash a array
profes= new String[llista_profes.size()];
profes = new String[llista_profes.size()];
Object[] keys = llista_profes.keySet().toArray();
for (int row = 0; row < llista_profes.size(); row++) {
profes[row] = (String)keys[row];
}
//Ordena el array
Arrays.sort(profes);
for (int j = 0; j < profes.length; j++) {
System.out.print("\n veiem profes::: " + profes[j]);
}
//imprimim el hash
System.out.println("\n Imprimim el hashmap amb la clau");
Iterator it = llista_profes.keySet().iterator();
while (it.hasNext()) {
String key = it.next().toString();
valor = llista_profes.get(key);
//Map.Entry e = (Map.Entry)it.next();
System.out.println(" -> Clau: " + valor );
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaFXApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
//**********************************************************************************
i = 0;
System.out.println("Començo a importar");
System.out.println("Matriu profes.length: " + profes.length);
System.out.println("Matriu grups.length: " + grups.length);
//Get scanner instance
Scanner scann;
try {
// compte amb la codificació, millor UTF-8
scann = new Scanner(new File("dades/horaris.csv"));
//Set the delimiter used in file
scann.useDelimiter(";");
//Get all tokens and store them in some data structure
//I am just printing them
while (scann.hasNext()) {
valor = scann.next();
// System.out.print("\n(" + i +") ");
// System.out.print(valor + " ");
matriu[i] = sensecometes(valor);
i = i + 1;
}
//Do not forget to close the scann
scann.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaFXApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
// Poblem la SuperMatriu amb '-' i posem 'P' a l'hora del pati
SuperMatriu = new char[grups.length][DIES][HORA];
for (int j = 0; j < grups.length; j++) {
for (int k = 0; k < DIES; k++) {
for (int m = 0; m < HORA; m++) {
if (m != 3){
SuperMatriu[j][k][m] = '-';
}else{
SuperMatriu[j][k][m] = 'p';
}
}
}
}
// Poblem la SuperMatriuProfes amb '-'
SuperMatriuProfes= new char[profes.length][DIES][HORA];
for (int j = 0; j < profes.length; j++) {
for (int k = 0; k < DIES; k++) {
for (int m = 0; m < HORA; m++) {
SuperMatriuProfes[j][k][m] = '-';
}
}
}
// fem una prova per mostrar classes per grups i canviar la SuperMatriu
for (int c = 0; c < grups.length; c++) {
System.out.print("\n grup: " + grups[c]);
cont_h_grup = 0;
for (int p = 0; p < matriu.length; p++) {
if (grups[c].equals(matriu[p])) {
System.out.print("\n grup: " + matriu[p]
+ " profe: " + matriu[(p + 1)]
+ " mater: " + matriu[(p + 2)]
+ " aula: " + matriu[(p + 3)]
+ " dia: " + matriu[(p + 4)]
+ " hora: " + matriu[(p + 5)]);
cont_h_grup++; // per veure el total de classe per al grup
//String enteroString = "5";
enteroDIA = Integer.parseInt((matriu[(p + 4)]));
enteroHORA = Integer.parseInt((matriu[(p + 5)]));
System.out.print("\n | " + enteroDIA + " | " + enteroHORA);
//si és abans del pati no fem res, si és després afegim l'hora del pati
if (enteroHORA - 1 < 3){
SuperMatriu[c][enteroDIA - 1][enteroHORA - 1] = 'X'; // Marco que està ocupat
}else{
SuperMatriu[c][enteroDIA - 1][enteroHORA] = 'X';
}
}
}
System.out.print("\n Total hores setmanals del grup: " + cont_h_grup);
}
// Ara imprimim els horaris de grups
for (int j = 0; j < grups.length; j++) {
System.out.print("\n horari de grup: " + grups[j]);
System.out.print(" \n ========================================= ");
for (int m = 0; m < HORA; m++) {
System.out.print("\n");
for (int k = 0; k < DIES; k++) {
System.out.print(SuperMatriu[j][k][m]);
}
}
}
// fem una prova per mostrar classes per grups i canviar la SuperMatriuProfes
for (int c = 0; c < profes.length; c++) {
System.out.print("\n profe: " + profes[c]);
cont_h_profe = 0;
for (int p = 0; p < matriu.length; p++) {
if (profes[c].equals(matriu[p])) {
System.out.print("\n grup: " + matriu[p]
+ " profe: " + matriu[(p)]
+ " mater: " + matriu[(p + 1)]
+ " aula: " + matriu[(p + 2)]
+ " dia: " + matriu[(p + 3)]
+ " hora: " + matriu[(p + 4)]);
cont_h_profe++; // per veure el total de classe per al grup
//String enteroString = "5";
enteroDIA = Integer.parseInt((matriu[(p + 3)]));
enteroHORA = Integer.parseInt((matriu[(p + 4)]));
System.out.print("\n | " + enteroDIA + " | " + enteroHORA);
//si és abans del pati no fem res, si és després afegim l'hora del pati
if (enteroHORA - 1 < 3){
SuperMatriuProfes[c][enteroDIA - 1][enteroHORA - 1] = 'X'; // Marco que està ocupat
}else{
SuperMatriuProfes[c][enteroDIA - 1][enteroHORA] = 'X';
}
}
}
System.out.print("\n Total hores setmanals del profe: " + cont_h_profe);
}
// Ara imprimim els horaris de profes
for (int j = 0; j < profes.length; j++) {
System.out.print("\n horari de profe: " + profes[j]);
System.out.print(" \n ========================================= ");
for (int m = 0; m < HORA; m++) {
System.out.print("\n");
for (int k = 0; k < DIES; k++) {
System.out.print(SuperMatriuProfes[j][k][m]);
}
}
}
//Inicialitzo la matriu de guardies amb els possibles nombres de guardians
//posem 4 profes de guàrdia a totes les hores per defecte
for ( int m = 0; m < DIES; m++){
for ( int r = 0; r < HORES_GUARDIA_DIA; r++){
matriuGuardies[m][r] = new int[4];
}
}
//posem 3 profes de guàrdia a 1a hora
matriuGuardies[0][0] = new int[3];
matriuGuardies[1][0] = new int[3];
matriuGuardies[2][0] = new int[3];
matriuGuardies[3][0] = new int[3];
matriuGuardies[4][0] = new int[3];
//posem 6 profes de guàrdia a l'hora del pati
matriuGuardies[0][3] = new int[6];
matriuGuardies[1][3] = new int[6];
matriuGuardies[2][3] = new int[6];
matriuGuardies[3][3] = new int[6];
matriuGuardies[4][3] = new int[6];
//************************************************************************************************
i = 0;
//creo un hashmap o alguna cosa similar
Map<String, Professor> map = new HashMap<>();
//creo profes
for (int j = 0; j < profes.length; j++) {
System.out.print("\n entro al hashmap el profe: " + profes[j]);
Professor profe1 = new Professor(profes[j]);
profe1.creahorariprofe();
profe1.calculaforats();
profe1.ompleforats();
profe1.imprimeix_llista_forats();
profe1.imprimeix_hores_terminals();
map.put(profes[j], profe1);
}
System.out.println("\n Horariiiiii");
// Imprimimos el Map con un Iterador
Iterator it = map.keySet().iterator();
Professor proferecollit;
while (it.hasNext()) {
String key = it.next().toString();
proferecollit = map.get(key);
System.out.println("Clau: " + key + " -> Valor: " + proferecollit.horari[0][0] + " amb possibles guàrdies: " + proferecollit.hores_guardia);
System.out.println("Forats: " + proferecollit.comptaforats);
System.out.println("Permanències: " + proferecollit.calculapermanencies());
proferecollit.imprimeix_horari();
proferecollit.imprimeix_hores_terminals();
}
//********************************************************************************
Button btn = new Button();
btn.setText("Importo CSV");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//************************************************************************
}
});
Button btn2 = new Button();
btn2.setText("creo horari");
Button btn3 = new Button();
btn3.setText("hashmap: entro dades primer de tot");
FlowPane root = new FlowPane(20, 20);
root.getChildren().addAll(btn, btn2, btn3);
root.setAlignment(Pos.CENTER);
btn2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//****************************************************************************
}
});
btn3.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//**********************************************************************************
}
});
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Importo horaris a veure què...");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
<file_sep># posaguardies
Una prova que comença el 17 de novembre de 2015
|
db88337f1ad499a58d6b863203007be6021794b5
|
[
"Markdown",
"Java"
] | 2
|
Java
|
tomasveraferrer/posaguardies
|
baab413d164f2f9a14c6dfdeb4dbeed694894f25
|
0b61211d5d25e9e4e4d6feaeaa8ae31356546773
|
refs/heads/master
|
<repo_name>Garviny/hep-download<file_sep>/hep-directory.js
let iframe = document.getElementsByTagName("iframe")[0];
if (iframe) {
location.href = iframe.src;
}
iframe = document.createElement("iframe");
document.body.appendChild(iframe);
window.console = iframe.contentWindow.console;
function init() {
let data = $vm.$children[0].$children[0].$children[0]._data;
let pageRes = data.impoweRes;
let directories = data.tableOfContentList;
let directoriesDom = document.querySelectorAll(".catalog-list li");
let ret = "";
for (let i = 0; i < directories.length; i++) {
let directory = directories[i];
let tab = parseInt(directoriesDom[i].style.textIndent) / 10;
tab = "\t".repeat(tab);
for (let j = 0; j < pageRes.length; j++) {
if (pageRes[j].Url.split("fn=")[1] === directory.page) {
ret += tab + directory.Title + "\t" + (j + 1) + "\r\n";
break;
}
}
}
exportRaw(data.readData.title, ret);
}
function exportRaw(name, data) {
let export_blob = new Blob([data], {type: "text/plain,charset=UTF-8"});
let save_link = document.createElement("a");
save_link.href = window.URL.createObjectURL(export_blob);
save_link.download = name;
save_link.click();
}
init();
|
9cdebe5ca89ecb61b44f20c0482d916588162094
|
[
"JavaScript"
] | 1
|
JavaScript
|
Garviny/hep-download
|
97e69a91baaa61c89943215380629d63daf6c53e
|
f5354edcf3c19f24dfb4dd74e3ae16bb5f02d790
|
refs/heads/master
|
<file_sep>function createPagenationStr(divId,count,numPerPage,pageIndex,callback){
$(".pagination",$("#"+divId)).html("");
$(".pagination",$("#"+divId)).append("<ul></ul>");
//当个数达不到翻页要求则不显示翻页
if(pageIndex == 1){
if(count <=numPerPage){
$(".pagination",$("#"+divId)).hide();
return;
}else{
$(".pagination",$("#"+divId)).show();
}
}
var index = Math.ceil(pageIndex/10) -1;
var prevActive = pageIndex>1 ? "":"disabled";
var nextActive = pageIndex<Math.ceil(count/numPerPage) ? "":"disabled";
if(prevActive == "disabled"){
$(".pagination ul",$("#"+divId)).append("<li class='prev "+prevActive+"'><a onclick=''>Prev</a></li>");
}else{
$(".pagination ul",$("#"+divId)).append("<li class='prev "+prevActive+"'><a onclick='"+callback+"("+(pageIndex-1)+","+numPerPage+")'>Prev</a></li>");
}
for(var i=0;i<10;i++){
if(index*10+i+1 > Math.ceil(count/numPerPage)) { break; }
if((index*10+i+1) == pageIndex){
$(".pagination ul",$("#"+divId)).append("<li class='active'><a onclick='"+callback+"("+(index*10+i+1)+","+numPerPage+")'>"+(index*10+i+1)+"</a></li>");
}else{
$(".pagination ul",$("#"+divId)).append("<li><a onclick='"+callback+"("+(index*10+i+1)+","+numPerPage+")'>"+(index*10+i+1)+"</a></li>");
}
}
if(nextActive == "disabled"){
$(".pagination ul",$("#"+divId)).append("<li class='next "+nextActive+"'><a onclick=''>Next</a></li>");
}else{
$(".pagination ul",$("#"+divId)).append("<li class='next "+nextActive+"'><a onclick='"+callback+"("+(pageIndex+1)+","+numPerPage+")'>Next</a></li>");
}
}
<file_sep>var Imap = require('imap')
var MailParser = require("mailparser").MailParser;
var fs = require("fs");
var imap = new Imap({
user : 'XXX',
password : 'XXX',
host : 'XXX',
port : 143,
tls : false,
tlsOptions : {
rejectUnauthorized : false
}
//,debug: console.log//调试信息
});
//html-to-text
var htmlToText = require('html-to-text');
var path = require('path');
function openInbox(cb) {
imap.openBox('XXX', false, cb);
//false:非只读模式
}
var messages = [];
var twoMinutes = 2 *1000 * 1;//30 *
// // one second = 1000 x 1 ms
// setInterval(function() {
imap.once('ready', function() {
openInbox(function(err, box) {
if (err)
throw err;
var f = imap.seq.fetch(box.messages.total, {
bodies : ''
});
f.on('message', function(msg, seqno) {
var mailparser = new MailParser();
var prefix = '(#' + seqno + ') ';
msg.on('body', function(stream, info) {
stream.pipe(mailparser);
//获取发件人
var buffer = '';
stream.on('data', function(chunk) {
buffer += chunk.toString('utf8');
});
mailparser.on("end", function(mail) {
var from = Imap.parseHeader(buffer)["from"];
from = from.toString().split("<")[1];
from = from.toString().split(">")[0];
console.log("----------------from:" + from);
fs.writeFile('msg-' + seqno + '-body.html', mail.html, function(err) {
if (err)
throw err;
console.log(seqno + 'saved!');
htmlToText.fromFile(path.join(__dirname, 'msg-' + seqno + '-body.html'), {
tables : ['#invoice', '.address']
}, function(err, text) {
if (err)
return console.error(err);
fs.writeFile('msg-' + seqno + '-body.txt', text, function(err) {
if (err)
throw err;
console.log(seqno + 'text saved!');
});
fs.unlink('msg-' + seqno + '-body.html', function(e) {
if (e) {
console.log(e);
} else
console.log('msg-' + seqno + '-body.html' + "delete succeed");
});
});
});
});
});
msg.once('end', function() {
console.log('prefix' + 'Finished');
});
msg.once('attributes', function(attrs) {
console.log(prefix + 'Attributes.uid: %s', attrs.uid);//inspect(attrs, false, 8)
// imap.addFlags(attrs.uid,'\DELETED',function(err){//添加删除标志
// if(err)
// console.log('Flags error: ' + err);
// });
// imap.expunge(attrs.uid,function(err){//彻底删除邮件
// if(err)
// console.log('EXPUNGE error: ' + err);
// imap.closeBox(function(err) {
// if (err) return cb(err);
// imap.logout(cb);
// });
// });
});
});
f.once('error', function(err) {
console.log('Fetch error: ' + err);
});
f.once('end', function() {
console.log('Done fetching all messages!');
imap.end();
});
});
});
imap.once('error', function(err) {
console.log(err);
});
imap.once('end', function() {
console.log('Connection ended');
});
imap.connect();
// }, twoMinutes);
<file_sep># exampleCode
一些好的示例代码
## 数据动态分页
* 包含pageAction.js和ajaxPaging.js
## mongodb游标查询
* mongo shell 中进行游标查询mongodbCursorFind
* 一个[json可视化工具](http://www.runoob.com/jsontool)
* mongo node.js中进行游标查询的方法:mongodbCursorFindEach
## mongodb更新表
* 插入字段:updateMongo
## node imap测试
* 读取邮件,并且解析内容、删除邮件。还有定时功能:readBoxAndExpunge.js
<file_sep>function initMyNodeData(pageIndex,numPerPage){
shareUserMap.clear();
$("#hideShareUser").html("");
allTableEmpty();
var activeTabHref = $("#nodeListDiv").find("#tabs-mynode").find("ul").find(".active").find("a").attr("href");
viewTableContent(activeTabHref, pageIndex, numPerPage);
ajaxPageing(pageIndex,numPerPage);
}
/**
* 动态分页
*
* @param {Object} pageIndex
* @param {Object} numPerPage
*/
function ajaxPageing(pageIndex,numPerPage){
$.ajax( {
type: 'GET',
url: apiURL + "/count/nodes/"+$("#nodeAuthor").html(),
data: {"isSelf":$("#isSelf").html(),"tagNameList":clickFilterTagList},
dataType: "json",
cache: false,
success: function(data) {
var nodeHtml = $("#nodeCount").html();
nodeHtml = nodeHtml.replace(/@nodeCount/,data.numCount);
$("#nodeCount").html(nodeHtml);
$("#nodeCount").show();
createPagenationStr("tabs-mynode",data.numCount,numPerPage,pageIndex,"initMyNodeData");
if(data.numCount == 0){
$("#Pagination_Search").html("");
return;
}
}
});
}
|
bc17382040027481814d93b575c610477b364c2b
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
pinkym/exampleCode
|
057ca202ca57f1d9f3385e0dd311a3f69e86388b
|
d4faf7ef6b73cbd2002c3369ef4d57c6f6e05dd3
|
refs/heads/master
|
<file_sep>using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.Base;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.List.Base
{
internal abstract class AListHtmlElt : ANestingHtmlElt
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Runs;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Runs.Base;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Standalone.Base;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Standalone
{
internal class ParagraphHtmlElt : AStandaloneHtmlElt
{
public ParagraphHtmlElt(IBodyElement bodyElement) : base(bodyElement)
{
if (Paragraph.NumLevelText != null)
{
IsInvalid = true;
return;
}
}
protected override string Tag => "p";
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Aesk.Docx2html.Host
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
private MainWindowViewModel ViewModel => (MainWindowViewModel) DataContext;
private void tb_Result_OnPreviewDragOver(object sender, DragEventArgs e)
{
var fileDrop = e.Data.GetData(DataFormats.FileDrop);
if (fileDrop == null)
{
e.Effects = DragDropEffects.None;
e.Handled = false;
return;
}
var pathes = (string[]) fileDrop;
if (pathes.Length != 1)
{
e.Effects = DragDropEffects.None;
e.Handled = false;
return;
}
var path = pathes[0];
if (System.IO.Path.GetExtension(path) != ".docx")
{
e.Effects = DragDropEffects.None;
e.Handled = false;
return;
}
e.Effects = DragDropEffects.Copy;
e.Handled = true;
}
private void tb_Result_OnDrop(object sender, DragEventArgs e)
{
var path = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
ViewModel.ParseDocx(path);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Prism.Mvvm;
namespace Aesk.Docx2html.Host.ViewModel
{
public class OptionsViewModel : BindableBase
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aesk.Docx2html.DocxParser.Imp;
using Aesk.Docx2html.DocxParser.Itf;
using Prism.Mvvm;
namespace Aesk.Docx2html.Host.ViewModel
{
public class ResultViewModel : BindableBase
{
private string _html;
public string Html
{
get { return _html; }
set { SetProperty(ref _html, value); }
}
}
}
<file_sep>using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Base
{
internal abstract class ADetactableHtmlElt : AnHtmlElt
{
protected readonly IBodyElement BodyElement;
protected ADetactableHtmlElt(IBodyElement bodyElement)
{
BodyElement = bodyElement;
}
}
}
<file_sep>using System;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Runs.Base;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Runs
{
internal class HyperlinkHtmlElt : ADocxRunHtmlElt
{
private static long _titlePrefixRandomizer = long.MinValue;
protected override string Tag => "a";
protected XWPFHyperlinkRun HlRun { get; }
protected override string Content { get; }
protected string Url { get; }
protected string Title { get; }
public HyperlinkHtmlElt(XWPFHyperlinkRun run) : base(run)
{
HlRun = run;
Content = run.Text;
Url = run.GetHyperlink(run.Paragraph.Document).URL;
Title = run.Text.Split(' ').Length == 1
? $"{(_titlePrefixRandomizer++ % 2 == 0 ? "Заказать" : "Купить")} {run.Text.ToLower()}"
: run.Text.Substring(0, 1).ToUpper() + run.Text.Substring(1, run.Text.Length - 1);
}
public override string ToString()
{
var content = Content;
return string.IsNullOrWhiteSpace(content)
? string.Empty
: $"<{Tag} href=\"{Url}\" title=\"{Title}\">{Content}</{Tag}>";
}
}
}
<file_sep>using System.Linq;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nested.Base;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.Base;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.List;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nested
{
internal class ListItemHtmlElt : ANestedHtmlElt
{
public static string[] UnorderedListItemsPrefixes =
{
"•",
};
protected override string Tag => "li";
protected override string Content { get; }
public ListItemHtmlElt(IBodyElement bodyElement) : base(bodyElement)
{
if (Paragraph.NumLevelText != null)
{
Content = Paragraph.Text;
return;
}
if (Paragraph.NumLevelText == null && UnorderedListItemsPrefixes.Any(i => Paragraph.Text.StartsWith(i)))
{
foreach (var i in UnorderedListItemsPrefixes)
{
if (Paragraph.Text.StartsWith(i))
{
Content = Paragraph.Text.Replace(i, string.Empty).Replace("\t", string.Empty);
break;
}
}
return;
}
IsInvalid = true;
}
public override ANestingHtmlElt ConstructParent()
{
if (Paragraph.NumLevelText == null)
{
return new UnorderedListHtmlElt();
}
if (Paragraph.NumLevelText.StartsWith("%"))
{
return new OrderedListHtmlElt();
}
return new UnorderedListHtmlElt();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace Aesk.Docx2html.DocxParser.Imp.Ext
{
internal static class EnumerableExt
{
public static TSource AggregateSafe<TSource>(
this IEnumerable<TSource> source,
Func<TSource, TSource, TSource> func)
=> source.Any()
? source.Aggregate(func)
: default(TSource);
}
}
<file_sep>using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Base;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Standalone.Base
{
internal abstract class AStandaloneHtmlElt : ADocxParagraphHtmlElt
{
protected AStandaloneHtmlElt(IBodyElement bodyElement) : base(bodyElement)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Base;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Runs.Base
{
internal abstract class ADocxRunHtmlElt : AnHtmlElt
{
protected XWPFRun Run { get; }
protected ADocxRunHtmlElt(XWPFRun run)
{
Run = run;
}
}
}
<file_sep>namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Base
{
internal abstract class AnHtmlElt
{
public bool IsInvalid { get; protected set; }
protected abstract string Tag { get; }
protected abstract string Content { get; }
public override string ToString()
{
var content = Content;
return string.IsNullOrWhiteSpace(content)
? string.Empty
: $"<{Tag}>{Content}</{Tag}>";
}
}
}
<file_sep>using System;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Base;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Comment
{
internal class CommentHtmlElt : ADetactableHtmlElt
{
public CommentHtmlElt(IBodyElement bodyElement) : base(bodyElement)
{
}
protected override string Tag
{
get { throw new ApplicationException($"Tag called for {this.GetType().FullName}");}
}
protected override string Content => BodyElement.ToString();
public override string ToString() => $"<!--Type:{BodyElement.ElementType} ToString={Content}-->";
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aesk.Docx2html.DocxParser.Itf
{
public interface IDocxParser
{
string Parse(string path);
}
}
<file_sep>using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.List.Base;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.List
{
internal class OrderedListHtmlElt : AListHtmlElt
{
protected override string Tag => "ol";
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Aesk.Docx2html.DocxParser.Imp.Ext;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Base;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nested.Base;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.Base
{
internal abstract class ANestingHtmlElt : AnHtmlElt
{
protected readonly LinkedList<ANestedHtmlElt> Children = new LinkedList<ANestedHtmlElt>();
public void Append(ANestedHtmlElt nestedHtmlElt)
{
Children.AddLast(nestedHtmlElt);
}
protected override string Content
{
get
{
return Children.Any()
? Children
.Select(i => i.ToString())
.Where(i => !string.IsNullOrWhiteSpace(i))
.Select(i => $"\t{i}{Environment.NewLine}")
.AggregateSafe((p, n) => p + n)
: string.Empty;
}
}
public override string ToString()
{
var content = Content;
return string.IsNullOrWhiteSpace(content)
? string.Empty
: $"<{Tag}>{Environment.NewLine}{Content}</{Tag}>";
}
}
}
<file_sep>using System;
using System.Linq;
using System.Text.RegularExpressions;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Comment
{
internal class CommentedTitleHtmlElt : CommentHtmlElt
{
private const string FIRST_RUN_REGEX_PATTERN = "^[0-9]?";
private static readonly Regex FirstRunRegex = new Regex(FIRST_RUN_REGEX_PATTERN);
public XWPFParagraph Paragraph { get; }
public CommentedTitleHtmlElt(IBodyElement bodyElement) : base(bodyElement)
{
if (bodyElement.ElementType != BodyElementType.PARAGRAPH)
{
IsInvalid = true;
return;
}
Paragraph = (XWPFParagraph)BodyElement;
if (Paragraph.NumLevelText != null)
{
IsInvalid = true;
return;
}
var runs = Paragraph.Runs.Where(i => !string.IsNullOrWhiteSpace(i.Text)).ToArray();
if (runs.Length < 2)
{
IsInvalid = true;
return;
}
if (!FirstRunRegex.IsMatch(runs[0].Text))
{
IsInvalid = true;
return;
}
Uri temp;
if (!Uri.TryCreate(runs[1].Text, UriKind.Absolute, out temp))
{
IsInvalid = true;
return;
}
Content = string.Join(string.Empty, runs.Select(i => i.Text)).Replace(Environment.NewLine, string.Empty);
}
protected override string Content { get; }
public override string ToString()
=> $"{Environment.NewLine}{Environment.NewLine}<!--PAGE LINK: {Content} -->{Environment.NewLine}{Environment.NewLine}";
}
}
<file_sep>using System.Linq;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Standalone.Base;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Standalone
{
internal class Header2HtmlElt : AStandaloneHtmlElt
{
public Header2HtmlElt(IBodyElement bodyElement) : base(bodyElement)
{
if (Paragraph.NumLevelText != null)
{
IsInvalid = true;
return;
}
if (Paragraph.Runs.Count == 0 || !Paragraph.Runs.First().IsBold)
{
IsInvalid = true;
return;
}
}
protected override string Tag => "h2";
}
}
<file_sep>using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Base;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.Base;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nested.Base
{
internal abstract class ANestedHtmlElt : ADocxParagraphHtmlElt
{
protected ANestedHtmlElt(IBodyElement bodyElement) : base(bodyElement)
{
}
public abstract ANestingHtmlElt ConstructParent();
}
}
<file_sep>using System;
using System.Text;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Runs;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp.HtmlElt.Base
{
internal abstract class ADocxParagraphHtmlElt : ADetactableHtmlElt
{
public XWPFParagraph Paragraph { get; }
protected ADocxParagraphHtmlElt(IBodyElement bodyElement) : base(bodyElement)
{
if (bodyElement.ElementType != BodyElementType.PARAGRAPH)
{
IsInvalid = true;
return;
}
Paragraph = (XWPFParagraph) BodyElement;
}
protected override string Content
{
get
{
var content = new StringBuilder();
foreach (var r in Paragraph.Runs)
{
var hlRun = r as XWPFHyperlinkRun;
if (hlRun != null)
{
var hl = new HyperlinkHtmlElt(hlRun);
content.Append(hl);
continue;
}
content.Append(r.Text);
}
return content.ToString().Replace(Environment.NewLine, string.Empty);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aesk.Docx2html.DocxParser.Imp.Ext;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Base;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nested.Base;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.Base;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.List;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Standalone.Base;
using Aesk.Docx2html.DocxParser.Itf;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp
{
public class NpoiDocxParser : IDocxParser
{
public string Parse(string path)
{
using (var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var doc = new XWPFDocument(stream);
return ToHtml(doc);
}
}
private string ToHtml(XWPFDocument doc)
{
var htmlElts = new LinkedList<AnHtmlElt>();
foreach (var be in doc.BodyElements)
{
ProcessBodyElement(be, ref htmlElts);
}
return htmlElts.Any()
? htmlElts
.Select(i => i.ToString())
.Where(i => !string.IsNullOrWhiteSpace(i))
.AggregateSafe((p, n) => p + Environment.NewLine + n)
: string.Empty;
}
private void ProcessBodyElement(IBodyElement bodyElt, ref LinkedList<AnHtmlElt> htmlElts)
{
var htmlElt = HtmlEltFactory.Construct(bodyElt);
if (htmlElt == null)
{
return;
}
var nestedHtmlElt = htmlElt as ANestedHtmlElt;
if (nestedHtmlElt != null)
{
var lastHtmlElt = htmlElts.Last.Value;
var lastNestingHtmlElt = lastHtmlElt as ANestingHtmlElt;
if (lastNestingHtmlElt == null)
{
lastNestingHtmlElt = HtmlEltFactory.ConstructParent(nestedHtmlElt);
htmlElts.AddLast(lastNestingHtmlElt);
}
lastNestingHtmlElt.Append(nestedHtmlElt);
return;
}
htmlElts.AddLast(htmlElt);
}
}
}
<file_sep>using System;
using System.Reflection;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Base;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Comment;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nested;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nested.Base;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.Base;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Nesting.List;
using Aesk.Docx2html.DocxParser.Imp.HtmlElt.Standalone;
using NPOI.XWPF.UserModel;
namespace Aesk.Docx2html.DocxParser.Imp
{
internal static class HtmlEltFactory
{
private static readonly Type[] DetectableHtmlEltTypes =
{
typeof(CommentedTitleHtmlElt),
typeof(ListItemHtmlElt),
typeof(Header2HtmlElt),
typeof(ParagraphHtmlElt),
typeof(CommentHtmlElt),
};
static HtmlEltFactory()
{
foreach (var i in DetectableHtmlEltTypes)
{
if (!typeof(ADetactableHtmlElt).IsAssignableFrom(i))
{
throw new ApplicationException($"{i.FullName} is not a {typeof(ADetactableHtmlElt).FullName}");
}
}
}
public static AnHtmlElt Construct(IBodyElement bodyElement)
{
AnHtmlElt result = null;
foreach (var i in DetectableHtmlEltTypes)
{
result = (AnHtmlElt)Activator.CreateInstance(i, bodyElement);
if (result.IsInvalid)
{
result = null;
}
else
{
break;
}
}
if (result == null)
{
throw new ApplicationException("Cannot cast docx body element to html element!!!");
}
return result;
}
public static ANestingHtmlElt ConstructParent(ANestedHtmlElt nestedHtmlElt)
=> nestedHtmlElt.ConstructParent();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Aesk.Docx2html.DocxParser.Imp;
using Aesk.Docx2html.DocxParser.Itf;
using Aesk.Docx2html.Host.ViewModel;
using Microsoft.Win32;
using Prism.Commands;
using Prism.Mvvm;
namespace Aesk.Docx2html.Host
{
public class MainWindowViewModel : BindableBase
{
private readonly IDocxParser _docxParser = new NpoiDocxParser();//fuck di
public ResultViewModel Result { get; } = new ResultViewModel();
public OptionsViewModel Options { get; } = new OptionsViewModel();
public ICommand SelectDocxCommand { get; }
public ICommand CopyToClipboardCommand { get; }
public MainWindowViewModel()
{
SelectDocxCommand = new DelegateCommand(SelectDocxDelegate);
CopyToClipboardCommand = new DelegateCommand(CopyToClipboardDelegate);
}
private void SelectDocxDelegate()
{
var dialog = new OpenFileDialog
{
Filter = "MS Word Open XML (*.docx)|*.docx",
Multiselect = false,
};
if (dialog.ShowDialog() == false)
{
return;
}
ParseDocx(dialog.FileName);
}
public void ParseDocx(string path)
{
Result.Html = _docxParser.Parse(path);
}
public void CopyToClipboardDelegate()
{
Clipboard.SetText(Result.Html);
}
}
}
|
d904571507c1050da331d22dad46fcd68f8f4f8a
|
[
"C#"
] | 23
|
C#
|
Aneskov/docx2html
|
2b00844c69c64f02ca5e9206bf3414a5b5f27fb0
|
736bf2704c126a816aa0e54749fd416a89ca4ab8
|
refs/heads/master
|
<file_sep>const { userModel } = require('../models');
const validators = require('./validators');
const createUser = async (req, res, next) => {
const value = validators.validate(req.body, validators.user.createUserSchema, next);
if (!value) return;
const { result, error } = await userModel.createUser(value);
if (error) return next(error);
res.send(result).status(200);
};
const getUser = async (req, res, next) => {
const { result, error } = await userModel.findOne({ email: req.params.email });
if (error) return next(error);
res.json(result).status(200);
};
const getUsers = async (req, res, next) => {
const { result, error } = await userModel.find({});
if (error) return next(error);
res.send(result).status(200);
};
const updateUserInfo = async (req, res, next) => {
const value = validators.validate(req.body, validators.user.updateUserSchema, next);
if (!value) return;
const { result, error } = await userModel.updateOne({ email: req.params.email }, value);
if (error) return next(error);
res.send(result).status(200);
};
module.exports = {
updateUserInfo,
createUser,
getUsers,
getUser,
};
<file_sep>module.exports = {
testEnvironment: 'node',
forceExit: true,
};
<file_sep>const { userModel } = require('../models');
exports.uploadFile = async (req, res, next) => {
const { result, error } = await userModel.findOneAndUpdate({
email: req.params.email }, { avatar: req.file.filename
});
if (error) return next(error);
res.status(200).send(result);
};
<file_sep>const _ = require('lodash');
const { userModel } = require('../../models');
const { dropDatabase } = require('../testHelper');
const userFactory = require('../factory/UserFactory');
describe('Check userModel', () => {
beforeEach(async () => {
await dropDatabase();
});
describe('Check create user', () => {
test('test create user', async () => {
const user = await userFactory.Create({ onlyData: true });
const { result, error } = await userModel.createUser(user);
expect(result).toBeDefined();
expect(error).toBeUndefined();
expect(user).toEqual(_.omit(result, ['__v', '_id']));
});
test('test create user undefined data', async () => {
const { result, error } = await userModel.createUser();
expect(result).toBeUndefined();
expect(error).toBeDefined();
});
});
describe('Check findOne user', () => {
let email, user;
beforeEach(async () => {
user = await userFactory.Create();
({ email } = user);
for (let i = 0; i < _.random(2, 8); i++) {
await userFactory.Create();
}
});
test('should find user by email', async () => {
const { result, error } = await userModel.findOne({ email });
expect(result).toBeDefined();
expect(error).toBeUndefined();
expect(user).toEqual(result);
});
});
});
<file_sep>const multer = require('multer');
const path = require('path');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './uploads');
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname)); // Appending extension
},
});
exports.upload = multer({ storage });
<file_sep>const supertest = require('supertest');
const models = require('../database');
const app = require('../index');
exports.request = supertest(app);
exports.dropDatabase = async () => {
for (const model in models) {
await models[model].deleteMany();
}
};
<file_sep>const faker = require('faker');
const { request } = require('../testHelper');
const { PATH } = require('../../constants/routesData');
jest.mock('../../models/userModel', () => ({ createUser: jest.fn().mockImplementation(() => ({ result: true })) }));
describe('Check userController', () => {
test('should return 200', async () => {
const response = await request
.post(`${PATH.USERS}`)
.send({
email: faker.random.word(),
password: <PASSWORD>(20),
});
expect(response.status).toBe(200);
});
test('should return 422', async () => {
const responseWithoutEmail = await request
.post(`${PATH.USERS}`)
.send({ password: <PASSWORD>(20) });
const responseWithoutPass = await request
.post(`${PATH.USERS}`)
.send({ email: faker.random.word(20) });
expect(responseWithoutEmail.status).toBe(422);
expect(responseWithoutPass.status).toBe(422);
});
});
<file_sep>const { Router } = require('express');
const userController = require('../controllers/userController');
const uploadController = require('../controllers/uploadController');
const uploadHelper = require('../helpers/uploadHelper');
const { PATH } = require('../constants/routesData');
const router = Router();
// region Users
router.route(`${PATH.USERS}`)
.get(userController.getUsers)
.post(userController.createUser);
router.route('/user/:email')
.get(userController.getUser)
.patch(userController.updateUserInfo);
// endregion
// region upLoad
router.route('/avatarUpload/:email')
.post(uploadHelper.upload.single('file'), uploadController.uploadFile);
// endregion
module.exports = { router };
<file_sep>const { User } = require('../database');
exports.createUser = async (data) => {
try {
const user = new User(data);
await user.save();
return { result: user.toObject() };
} catch (error) {
return { error };
}
};
exports.find = async (filter) => {
try {
return { result: await User.find(filter).lean() };
} catch (error) {
return { error };
}
};
exports.findOne = async (filter) => {
try {
return { result: await User.findOne(filter).lean() };
} catch (error) {
return { error };
}
};
exports.updateOne = async (filter, updateData) => {
try {
return { result: await User.updateOne(filter, updateData).lean() };
} catch (error) {
return { error };
}
};
exports.findOneAndUpdate = async (filter, updateData) => {
try {
return { result: await User.findOneAndUpdate(filter, updateData, { new: true }).lean() };
} catch (error) {
return { error };
}
};
|
c0ec7284e6a2d24233cead87a8679a952abec413
|
[
"JavaScript"
] | 9
|
JavaScript
|
Fesmofet/expressExample
|
ae446e48fcd9a0f516ced3896e4cd3fd93a2b8b0
|
2093b18c90dd70feb2a705fe160bcb0c3dd320c6
|
refs/heads/main
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SwitchQ : MonoBehaviour
{
public GameObject QKillButton, QTalkButton;
public IEnumerator WaitForSwitch(Image clicker)
{
yield return new WaitForSeconds(0.2f);
clicker.raycastTarget= true;
Debug.Log("Enabled");
}
public void Switch(Image button)
{
StartCoroutine(WaitForSwitch(button));
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pressQ : MonoBehaviour
{
public bool Qpress;
public GameObject[] ObjToDisable;
public GameObject aniObj;
public Animator ani;
private void Update()
{
if (Qpress)
{
Qpress = false;
aniObj.SetActive(true);
foreach (GameObject obj in ObjToDisable)
{
obj.SetActive(false);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlickerScript1 : MonoBehaviour
{
[HideInInspector]
public SpriteRenderer spriteR;
float switcher,randMax=1f;
public float totalFlickers, minFlickersToChangeSpeed = 2f;
//public float totalFlickers;
public Material mat1,mat2;
AudioManager audioManager;
private void Awake()
{
spriteR = GetComponent<SpriteRenderer>();
audioManager = FindObjectOfType<AudioManager>();
}
private void Start()
{
Debug.Log(spriteR.material);
StartCoroutine(FlickerLight());
}
IEnumerator FlickerLight()
{
while (totalFlickers>0)
{
yield return new WaitForSeconds(Random.Range(0f, randMax));
switcher++;
switch (switcher%2)
{
case 0: spriteR.material = mat1;totalFlickers--; audioManager.Play("LightFlicker"); break;
case 1: spriteR.material = mat2;break;
}
if (totalFlickers < minFlickersToChangeSpeed)
{
randMax = 0.2f;
}
}
if(totalFlickers == 0)
{
totalFlickers = 5f;
randMax = 1f;
StartCoroutine(FlickerLight());
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeGrav : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.layer == 9)
{
Rigidbody2D playerRigidbody = collision.gameObject.GetComponent<Rigidbody2D>();
playerRigidbody.gravityScale = 0.25f;
playerRigidbody.mass = 5f;
playerRigidbody.drag = 5f;
Debug.Log("Ran gravityScale script");
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EventControlMobile : MonoBehaviour
{
public Mover playerScript;
float x;
float t;
public QtoKill death;
PauseMenuScript pauseMenu;
private void Awake()
{
pauseMenu = FindObjectOfType<PauseMenuScript>();
}
public void Jump()
{
playerScript.jump = true;
playerScript.timeJumpStart = Time.time;
}
public void DashZ()
{
playerScript.dash = true;
}
public void QKill()
{
death.deathQ = true;
}
public void PauseButton()
{
pauseMenu.escaped = true;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeathAdController : MonoBehaviour
{
public float totalDeaths = 0f;
AdsController adsController;
private void Awake()
{
adsController = FindObjectOfType<AdsController>();
}
public void AddDeath()
{
totalDeaths += 1f;
if (totalDeaths %7f==0)
{
adsController.ShowInterstitialAd();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class QController : MonoBehaviour
{
pressQ qObj;
public GameObject pressQObj;
public GameObject enableText,button;
public BoxCollider2D boxColliderDialogue;
public bool qInCollider;
public void PressQ()
{
qObj = FindObjectOfType<pressQ>();
if (qObj)
{
enableText.SetActive(true);
button.SetActive(true);
qObj.Qpress = true;
Debug.Log("Turned Qpress on");
}
else
{
if (qInCollider)
{
pressQObj.SetActive(true);
}
}
}
}
<file_sep># Q2
Mobile 2D game project
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class spikesScirpt : MonoBehaviour
{
public GameObject playerObj,target;
public float respawnWaitTime=1.5f;
public bool level1,fallKill;
public bool gravityInvert,gravityWillChange;
AudioManager audioManager;
public GameObject deathParitcle;
public CinemachineVirtualCamera vrcam;
GameObject spawnedObj;
public bool extraLevel;
DeathAdController deathAdController;
private CameraShake shaker;
private void Awake()
{
audioManager = FindObjectOfType<AudioManager>();
deathAdController = FindObjectOfType<DeathAdController>();
}
private void Start()
{
shaker = FindObjectOfType<CameraShake>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 9)
{
shaker.CameraShaker(5f, 8f, 0f);
deathAdController.AddDeath();
Time.timeScale = 0.75f;
if (!fallKill)
{
Instantiate(deathParitcle, collision.transform.position, transform.rotation);
}
audioManager.Play("Death");
Destroy(collision.gameObject);
StartCoroutine(WaitRespawn());
}
}
public IEnumerator WaitRespawn()
{
yield return new WaitForSeconds(respawnWaitTime);
spawnedObj = Instantiate(playerObj, target.transform.position, target.transform.rotation);
if (gravityInvert)
{
spawnedObj.GetComponent<ChangeGravController>().audioManager = audioManager;
}
if (extraLevel)
{
//
}
else
{
spawnedObj.GetComponent<Mover>().audioManager = audioManager;
}
if (gravityWillChange)
{
Physics2D.gravity = new Vector2(0, -9.81f);
}
if (!level1)
{
QtoKill newPlayerScript = spawnedObj.GetComponent<QtoKill>();
newPlayerScript.targetObj = target;
newPlayerScript.vrcam = vrcam;
newPlayerScript.playerObj = playerObj;
}
Vector3 SettingZ = spawnedObj.transform.position;
SettingZ.z = 0;
spawnedObj.transform.position = SettingZ;
vrcam.Follow = spawnedObj.transform;
Time.timeScale = 1f;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class QtoKill : MonoBehaviour
{
public float respawnWaitTime=1f;
public GameObject playerObj, targetObj,deathObj;
GameObject spawnedObj;
public CinemachineVirtualCamera vrcam;
Rigidbody2D rb;
public AudioManager audioManager;
[HideInInspector]
public BoxCollider2D boxCol;
[HideInInspector]
public SpriteRenderer sprite;
public bool deathQ;
private void Awake()
{
EventControlMobile eventMobile = FindObjectOfType<EventControlMobile>();
eventMobile.death = GetComponent<QtoKill>();
}
private void Start()
{
rb = GetComponent<Rigidbody2D>();
sprite = GetComponent<SpriteRenderer>();
boxCol = GetComponent<BoxCollider2D>();
audioManager = FindObjectOfType<AudioManager>();
}
private void Update()
{
if (deathQ)
{
sprite.enabled = false;
GameObject enemyObj = Instantiate(deathObj, transform.position, transform.rotation);
RandomForce[] enemyObjs = enemyObj.GetComponentsInChildren<RandomForce>();
foreach (RandomForce enemyScript in enemyObjs)
{
enemyScript.playerRbVel = rb.velocity;
}
Time.timeScale = 0.75f;
StartCoroutine(WaitRespawn());
deathQ = false;
}
}
public IEnumerator WaitRespawn()
{
audioManager.Play("Death");
yield return new WaitForSeconds(respawnWaitTime);
spawnedObj = Instantiate(playerObj, targetObj.transform.position, targetObj.transform.rotation);
Vector3 targetPos = spawnedObj.transform.position;
targetPos.z = 0;
spawnedObj.transform.position = targetPos;
QtoKill newPlayerScript = spawnedObj.GetComponent<QtoKill>();
newPlayerScript.vrcam = vrcam;
newPlayerScript.targetObj = targetObj;
newPlayerScript.deathObj = deathObj;
newPlayerScript.playerObj = playerObj;
vrcam.Follow = spawnedObj.transform;
Time.timeScale = 1f;
Destroy(gameObject);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpeedIncreaseFast : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 9)
{
collision.gameObject.GetComponent<ChangeGravController>().speed += 5f;
Debug.Log("Speed increased!");
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GravityChange : MonoBehaviour
{
public bool gravityUp = false;
AudioManager audioManager;
private void Awake()
{
audioManager = FindObjectOfType<AudioManager>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.layer == 9)
{
if (gravityUp)
{
switch (Physics2D.gravity == new Vector2(0, -9.81f))
{
case true: Physics2D.gravity = new Vector2(0, 9.81f); audioManager.Play("GravityChange"); break;
case false: break;
}
}
else
{
switch (Physics2D.gravity == new Vector2(0,9.81f))
{
case true: Physics2D.gravity = new Vector2(0, -9.81f);audioManager.Play("GravityChange");break;
case false: break;
}
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Cinemachine;
public class NextLevel : MonoBehaviour
{
public GameObject canvasObj,playerObj,target;
public SpriteRenderer backgroundPortal;
public Animator canvasAni,controlsAni;
AudioManager audioManager;
public CinemachineVirtualCamera vrcam;
public bool line2, line4, line6;
private void Awake()
{
audioManager = FindObjectOfType<AudioManager>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.layer == 9)
{
collision.gameObject.SetActive(false);
controlsAni.SetTrigger("ControlEnding");
LoadAni();
}
}
public void LoadAni()
{
StartCoroutine(Waiter());
}
public IEnumerator Waiter()
{
yield return null;
Time.timeScale = 0f;
//aniPlayerObj.SetTrigger("changeIntensity");
vrcam.Follow = target.transform;
canvasObj.SetActive(true);
playerObj.SetActive(false);
canvasAni.SetTrigger("fadeInAni");
//aniObj.SetTrigger("changeIntensity");
AsyncOperation sceneLoader = SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex + 1);
sceneLoader.allowSceneActivation = false;
Time.timeScale = 1f;
if (line2)
{
audioManager.Play("Line2");
}
else if (line4)
{
audioManager.Play("Line4");
}
else if (line6)
{
audioManager.Play("Line6");
}
yield return new WaitForSeconds(2f);
sceneLoader.allowSceneActivation = true;
//StartCoroutine(WaitSceneLoad(sceneLoader));
}
public IEnumerator WaitSceneLoad(AsyncOperation sceneLoader)
{
yield return null;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class NewLevelController : MonoBehaviour
{
public GameObject canvasObj ,portalMask,playerObj;
public Animator canvasAni, childAni;
public bool antiGravLevel;
public CinemachineVirtualCamera cvcam;
private void Awake()
{
Time.timeScale = 0f;
canvasObj.SetActive(true);
portalMask.SetActive(false);
canvasAni.SetTrigger("fadeoutAni");
childAni.SetTrigger("endingTrig");
}
private void Update()
{
if (!AnimatorIsPlaying(canvasAni))
{
Debug.Log("Animation Completed");
canvasObj.SetActive(false);
portalMask.SetActive(true);
playerObj.SetActive(true);
Time.timeScale = 1f;
if (antiGravLevel)
{
cvcam.m_Lens.OrthographicSize = 7.5f;
}
gameObject.SetActive(false);
}
}
bool AnimatorIsPlaying(Animator animator)
{
return animator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeGravController : MonoBehaviour
{
float horizontalAx;
bool canDash;
public bool jump, isGrounded, dash, slam, can_jump,qPress;
Rigidbody2D rb;
public float speed = 10f, jumpForce = 5f, increasedGrav = 2f, dashForce = 5f, slamForce = 4f, dashCooldown = 2f;
public Transform groundCheckPos;
public GameObject death_obj;
public AudioManager audioManager;
[HideInInspector]
public GameObject marker;
EventControlMobile2 eventController;
//public LayerMask groundLayer;
public Vector2 playerVel;
private void Awake()
{
eventController = FindObjectOfType<EventControlMobile2>();
eventController.changeGrav = GetComponent<ChangeGravController>();
}
void Start()
{
rb = GetComponent<Rigidbody2D>();
marker = this.gameObject;
Time.timeScale = 1f;
}
void Update()
{
playerVel = rb.velocity;
horizontalAx = Input.GetAxisRaw("Horizontal");
if (qPress)
{
audioManager.Play("GravityChange");
Physics2D.gravity *= -1;
qPress = false;
}
/*
slam = Input.GetKeyDown(KeyCode.S);
if (slam && !isGrounded)
{
rb.AddForce(Vector2.down * 100 * slamForce);
}
if (Input.GetButtonDown("Jump"))
{
jump = true;
}
if (Input.GetButtonUp("Jump"))
{
jump = false;
}/
if (Input.GetKeyDown(KeyCode.Z) && horizontalAx != 0)
{
if (timeEnd - timeStart > dashCooldown || canDash)
{
rb.AddForce(new Vector2(horizontalAx, 0) * dashForce);
timeStart = Time.time;
canDash = false;
}
}
}
private void FixedUpdate()
{
if (rb.velocity.y <= 0)
{
rb.AddForce(new Vector2(0, -1) * increasedGrav);
}
transform.Translate(Vector2.right * horizontalAx * Time.fixedDeltaTime * speed);
if (jump && isGrounded)
{
rb.velocity = Vector2.zero;
rb.AddForce(Vector2.up * 100 * jumpForce);
jump = false;
}*/
}
private void FixedUpdate()
{
transform.Translate(Vector2.right * horizontalAx * Time.fixedDeltaTime * speed);
}
private void OnDestroy()
{
GameObject enemyObj = Instantiate(death_obj, transform.position, transform.rotation);
RandomForce[] enemyObjs = enemyObj.GetComponentsInChildren<RandomForce>();
foreach (RandomForce enemyScript in enemyObjs)
{
enemyScript.playerRbVel = playerVel;
}
Time.timeScale = 0.75f;
new WaitForSeconds(1f);
Time.timeScale = 1f;
}
public void CameraShake()
{
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CheckPoint : MonoBehaviour
{
public GameObject particleObj,targetParticle;
public GameObject[] objectsToDisable,objectsToEnable;
public GameObject[] portalObjsToMove;
public GameObject newPortalTarget;
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.layer == 9)
{
foreach (GameObject obj in objectsToDisable)
{
Destroy(obj);
}
foreach (GameObject portalObj in portalObjsToMove)
{
MovePortal(portalObj);
}
foreach (GameObject enableObj in objectsToEnable)
{
enableObj.SetActive(true);
}
Instantiate(particleObj, targetParticle.transform.position, targetParticle.transform.rotation);
Destroy(this.gameObject);
}
}
private void MovePortal(GameObject ObjToMove)
{
Vector3 newPos = ObjToMove.transform.position;
newPos.x = newPortalTarget.transform.position.x;
ObjToMove.transform.position = newPos;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class QtoInteract : MonoBehaviour
{
public GameObject QInteract;
public Animator textBoxAni;
public PlayScript playScript;
public QController qController;
public GameObject QKillButton, QTextButton;
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.layer == 9)
{
QInteract.SetActive(true);
if (QKillButton != null)
{
QKillButton.SetActive(false);
QTextButton.SetActive(true);
}
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (QKillButton != null)
{
QKillButton.SetActive(true);
QTextButton.SetActive(false);
}
qController.qInCollider = false;
playScript = FindObjectOfType<PlayScript>();
if (playScript == null)
{
textBoxAni.SetTrigger("endTalking");
StartCoroutine(waitTurnFalse());
}
else if(playScript != null)
{
if (playScript.loadAniEnd == false)
{
playScript.loadAniEnd = true;
Debug.Log("loadAni is false");
}
else
{
playScript.loadAniEnd = true;
textBoxAni.SetTrigger("endTalking");
StartCoroutine(waitTurnFalse());
}
}
else
{
playScript.loadAniEnd = true;
textBoxAni.SetTrigger("endTalking");
StartCoroutine(waitTurnFalse());
}
}
private IEnumerator waitTurnFalse()
{
yield return new WaitForSeconds(0.3f);
QInteract.SetActive(false);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StartFlicker : MonoBehaviour
{
public GameObject flickerSign;
public Material mat1, mat2;
public AudioManager audioManager;
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.layer == 9)
{
FlickerScript flickerScript = flickerSign.AddComponent<FlickerScript>();
flickerScript.mat1 = mat1;
flickerScript.mat2 = mat2;
Debug.Log("Added Component");
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using Cinemachine;
using UnityEngine;
public class CameraShake : MonoBehaviour
{
float x;
float t;
bool runPerl,canWork;
public CinemachineVirtualCamera cvcam;
public void CameraShaker(float speedFadeIn,float maxAmplitude,float minAmplitude)
{
runPerl = true;
canWork = true;
StartCoroutine(Shaker(speedFadeIn,maxAmplitude,minAmplitude));
//cvcam.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>().m_AmplitudeGain = 0f;
}
IEnumerator Shaker(float speedFadeIn,float maxAmplitude,float minAmplitude)
{
CinemachineBasicMultiChannelPerlin cvcamNoise = cvcam.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
while (runPerl)
{
x = Mathf.Lerp(minAmplitude, maxAmplitude, t);
t += speedFadeIn * Time.deltaTime;
cvcamNoise.m_AmplitudeGain = x;
if (x==maxAmplitude)
{
runPerl = false;
t = 0;
}
yield return null;
}
while (!runPerl && canWork)
{
x = Mathf.Lerp(maxAmplitude, minAmplitude, t);
t += speedFadeIn * Time.deltaTime;
cvcamNoise.m_AmplitudeGain = x;
if (x == minAmplitude)
{
canWork = false;
cvcamNoise.m_AmplitudeGain = 0f;
t = 0;
x = 0;
}
yield return null;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class ZoomOut : MonoBehaviour
{
public CinemachineVirtualCamera cvcam;
private float t=0f,startVal;
public float assignedVal = 12f;
private bool lerpVal,notWork;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 9 && cvcam.m_Lens.OrthographicSize != 10f)
{
if (t < 1)
{
lerpVal = true;
startVal = cvcam.m_Lens.OrthographicSize;
Debug.Log(startVal);
}
}
}
IEnumerator LerpValues()
{
yield return null;
cvcam.m_Lens.OrthographicSize = Mathf.Lerp(startVal, assignedVal, t);
t += 0.5f * Time.deltaTime;
}
private void Update()
{
if (lerpVal)
{
StartCoroutine(LerpValues());
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class EventController : MonoBehaviour
{
public AudioManager audioManager;
public Animator MainMenuAni;
public void Play()
{
MainMenuAni.SetTrigger("MainMenuAni");
AsyncOperation asyncOp = SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex + 1);
asyncOp.allowSceneActivation = false;
StartCoroutine(MainWait(asyncOp));
audioManager.Play("Line1");
}
public void Quit()
{
Application.Quit();
Debug.Log("Quit Game!");
}
IEnumerator MainWait(AsyncOperation asyncOp)
{
yield return new WaitForSeconds(2.1f);
asyncOp.allowSceneActivation = true;
}
public void OnClick()
{
audioManager.Play("Click");
}
public void onHover()
{
audioManager.Play("Hover");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayLines : MonoBehaviour
{
AudioManager audioManager;
public string clipName;
private void Awake()
{
audioManager = FindObjectOfType<AudioManager>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
audioManager.Play("Line2");
Destroy(gameObject);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenuScript : MonoBehaviour
{
public GameObject pauseMenu,controlUI;
public bool isPaused,escaped;
public Animator pauseMenuAni;
public AudioManager audioManager;
private void Update()
{
if (escaped && !isPaused)
{
escaped = false;
Pause();
isPaused = true;
Debug.Log("Paused");
}
else if(escaped && isPaused)
{
Resume();
isPaused = false;
}
}
public void Pause()
{
pauseMenu.SetActive(true);
Time.timeScale = 0f;
controlUI.SetActive(false);
}
public void Resume()
{
controlUI.SetActive(true);
pauseMenuAni.SetTrigger("ResumeAniTrigger");
Time.timeScale = 1f;
isPaused = false;
//controlUI.SetActive(true);
StartCoroutine(resumeWait());
}
public void GoToMainMenu()
{
SceneManager.LoadScene(0);
Debug.Log("Go to MainMenu");
}
public void QuitButton()
{
Application.Quit();
Debug.Log("Application Quit");
}
IEnumerator resumeWait()
{
yield return new WaitForSeconds(0.183f);
pauseMenu.SetActive(false) ;
escaped = false;
}
public void OnClick()
{
audioManager.Play("Click");
}
public void onHover()
{
audioManager.Play("Hover");
}
bool AnimatorIsPlaying(Animator animator)
{
return animator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class PlayScript : MonoBehaviour
{
public Image button;
public bool buttonEnabled;
public string[] lines;
public TextMeshPro text;
int i;
public GameObject[] disableObjs;
public GameObject[] enableObjs;
public Animator cinemaAni,TextBoxAni;
public GameObject cinemaCanvasObj;
public GameObject TextBoxObj;
public QController qController;
public bool loadAniEnd= true;
public DeathAdController deaths;
public GameObject QKillButton, QTextButton;
public SwitchQ swticher;
private IEnumerator LineWait()
{
string[] hiInLanguages = { "Howdy :D", "Konichiwa box-San", "Heya ;D", "Salut mon ami :D", "Wassup Homie ( ͡❛ ͜ʖ ͡❛)", "Namaste :D", "ni-hao :D", "( ͡ಠ ͜ʖ ͡ಠ)", "Hello :D" };
List<string> hiList = new List<string>(hiInLanguages);
text.text = " ";
if(lines[i]=="...!!")
{
deaths = FindObjectOfType<DeathAdController>();
lines[i] = ". . . Look youve already died a total of " + deaths.totalDeaths + " times . . .";
}
if (hiList.Contains(lines[i]))
{
lines[i] = hiList[Random.Range(0, 9)];
}
foreach (char letter in lines[i])
{
text.text += letter;
yield return new WaitForSeconds(0.05f);
}
}
public void StartNewLine()
{
StopAllCoroutines();
//StopCoroutine(LineWait());
i++;
if (i < lines.Length)
{
text.text = "";
StartCoroutine(LineWait());
Debug.Log("Started new Line!");
}
else
{
foreach (GameObject disableObj in disableObjs)
{
disableObj.SetActive(false);
}
Debug.Log("Started Ending Sequence");
EndBox();
}
}
public void EndBox()
{
if (buttonEnabled)
{
button.raycastTarget = false;
Debug.Log("Enabled Button");
}
qController.qInCollider = true;
text.text = "";
loadAniEnd = false;
i = -1;
cinemaAni.SetTrigger("cinemaOutAni");
TextBoxAni.SetTrigger("endTalking");
foreach (GameObject enableObj in enableObjs)
{
enableObj.SetActive(true);
}
if (QKillButton != null)
{
}
StartCoroutine(WaitCinemaDisable());
}
IEnumerator WaitCinemaDisable()
{
yield return new WaitForSeconds(0.5f);
StartCoroutine(waitTurnFalse());
cinemaCanvasObj.SetActive(false);
}
private void Start()
{
loadAniEnd = true;
StartCoroutine(LineWait());
}
private IEnumerator waitTurnFalse()
{
yield return new WaitForSeconds(0.3f);
if (buttonEnabled)
{
swticher.Switch(button);
}
TextBoxObj.SetActive(false);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScrollScript : MonoBehaviour
{
public GameObject spikeObj,target;
public Transform parent;
private void OnTriggerEnter2D(Collider2D collision)
{
GameObject spawnedObj = Instantiate(spikeObj, target.transform.position, target.transform.rotation);
spawnedObj.transform.SetParent(parent);
ScrollScript scriptObj = spawnedObj.GetComponent<ScrollScript>();
scriptObj.target = target;
scriptObj.parent = parent;
Destroy(gameObject);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RandomForce : MonoBehaviour
{
public Rigidbody2D rb;
[HideInInspector]
public Vector2 playerRbVel;
public Rigidbody2D playerObj;
public float explosionForce = 20f;
private void Start()
{
rb.velocity = playerRbVel;
rb.AddForce(new Vector2(Random.Range(100f,-100), Random.Range(100f, -100)) * explosionForce);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Recording : MonoBehaviour
{
public GameObject playerObj;
List<Vector2> recordingPositions = new List<Vector2>();
private void FixedUpdate()
{
recordingPositions.Add(playerObj.transform.position);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class Mover1 : MonoBehaviour
{
float horizontalAx,timeStart,timeEnd;
bool canDash,shakeCam;
public bool jump,isGrounded,dash,slam,can_jump,canMove,SwitchMoveStyles;
Rigidbody2D rb;
public float speed = 10f,jumpForce = 5f,increasedGrav=2f,dashForce=5f,slamForce=4f,dashCooldown = 2f,timeJumpStart;
public Transform groundCheckPos,topGroundCheck;
public GameObject death_obj;
[HideInInspector]
public GameObject marker;
public LayerMask groundLayer;
public Vector2 playerVel;
public AudioManager audioManager;
public GameObject DashParticle,JumpParticle,LandParticle;
[Header("Shaker")]
public float shakeTime = 2f, fadeCamShake = 2f,maxAmplitude = 4f,minAmplitude = 0f;
CameraShake shaker;
float starter,ender;
public Joystick joystick;
public EventControlMobile1 eventController;
private void Awake()
{
audioManager = FindObjectOfType<AudioManager>();
joystick = FindObjectOfType<FixedJoystick>();
eventController = FindObjectOfType<EventControlMobile1>();
eventController.playerScript = GetComponent<Mover1>();
}
void Start()
{
shaker = FindObjectOfType<CameraShake>();
rb = GetComponent<Rigidbody2D>();
timeStart = Time.time;
marker = this.gameObject;
Time.timeScale = 1f;
}
void Update()
{
timeEnd = Time.time;
playerVel = rb.velocity;
bool negativeGrav = Physics2D.gravity.y <0f;
if ((Physics2D.OverlapCircle(groundCheckPos.position, 0.3f, groundLayer) && negativeGrav) || (Physics2D.OverlapCircle(topGroundCheck.position, 0.3f, groundLayer) && !negativeGrav))
{
starter = Time.time;
isGrounded = true;
canDash = true;
canMove = true;
if (shakeCam)
{
Instantiate(LandParticle, transform.position, transform.rotation);
shaker.CameraShaker(fadeCamShake,maxAmplitude,minAmplitude);
shakeCam = false;
}
}
else
{
ender = Time.time;
isGrounded = false;
if (SwitchMoveStyles)
{
canMove = false;
}
}
if ((ender - starter) > shakeTime)
{
shakeCam = true;
}
if (joystick.Horizontal >= 0.4f)
{
horizontalAx = 1f;
}
else if (joystick.Horizontal <= -0.4f)
{
horizontalAx = -1f;
}
else
{
horizontalAx = 0f;
}
float verticalJoystick = joystick.Vertical;
if (verticalJoystick >= 0.8f)
{
jump = true;
timeJumpStart = Time.time;
}
slam = Input.GetKeyDown(KeyCode.S);
if(slam && !isGrounded)
{
rb.AddForce(Vector2.down * 100 * slamForce);
}
/* if (Input.GetButtonDown("Jump"))
{
jump = true;
timeJumpStart = Time.time;
}
*/
if (dash && (Mathf.Abs(horizontalAx)>0))
{
if (timeEnd - timeStart > dashCooldown || canDash)
{
rb.AddForce(new Vector2(horizontalAx, 0) * dashForce);
audioManager.Play("Dash");
if(horizontalAx >0.01f)
{
GameObject particleDash = Instantiate(DashParticle, transform.position, transform.rotation);
particleDash.transform.localScale = new Vector3(-1,1,1);
}
else if(horizontalAx<0.01f)
{
Instantiate(DashParticle, transform.position, transform.rotation);
}
shaker.CameraShaker(5f , 6f, 0f);
timeStart = Time.time;
canDash = false;
}
dash = false;
}
}
private void FixedUpdate()
{
if (rb.velocity.y < 0 && Physics2D.gravity.y==-9.81f && !isGrounded)
{
rb.AddForce(new Vector2(0, -1)*increasedGrav);
}
else if(rb.velocity.y > 0 && Physics2D.gravity.y == 9.81f && !isGrounded)
{
rb.AddForce(new Vector2(0, 1) * increasedGrav);
}
transform.Translate(Vector2.right * horizontalAx * Time.fixedDeltaTime * speed);
if (jump && isGrounded && Time.time - timeJumpStart<=0.2f)
{
audioManager.Play("Jump");
shaker.CameraShaker(5f, 6f, 0f);
rb.velocity = Vector2.zero;
rb.AddForce(Vector2.up * 100 * jumpForce * -Mathf.Clamp(Physics2D.gravity.y, -1f, 1f));
Debug.Log(-Mathf.Clamp(Physics2D.gravity.y, -1f, 1f));
if (Physics2D.gravity.y == -9.81f)
{
Instantiate(JumpParticle, transform.position, transform.rotation);
}
else
{
Instantiate(JumpParticle, transform.position, transform.rotation).transform.localScale*=-1f;
}
jump = false;
}
}
private void OnDestroy()
{
GameObject enemyObj = Instantiate(death_obj, transform.position, transform.rotation);
RandomForce[] enemyObjs = enemyObj.GetComponentsInChildren<RandomForce>();
foreach (RandomForce enemyScript in enemyObjs)
{
enemyScript.playerRbVel = playerVel;
}
Time.timeScale = 0.75f;
new WaitForSeconds(1f);
Time.timeScale = 1f;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyAfterSomeTIme : MonoBehaviour
{
float timeStart, timeEnd;
private void Awake()
{
timeStart = Time.time;
Debug.Log(timeStart);
}
private void Update()
{
timeEnd = Time.time;
if(timeEnd-timeStart>5f)
{
Destroy(gameObject);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayEndingAni : MonoBehaviour
{
public Animator ani;
public GameObject AniObj;
public GameObject disableObj;
AsyncOperation loadScene;
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 9)
{
StartCoroutine(PlayAniWait());
StartCoroutine(EndEndngSequence());
StartCoroutine(ChangeLevel());
}
}
IEnumerator PlayAniWait()
{
Debug.Log("working");
yield return new WaitForSeconds(4f);
AniObj.SetActive(true);
disableObj.SetActive(false);
Debug.Log("Wait working");
ani.SetTrigger("EndingAni");
loadScene = SceneManager.LoadSceneAsync(0);
loadScene.allowSceneActivation = false;
}
IEnumerator EndEndngSequence()
{
yield return new WaitForSeconds(17f);
Debug.Log("Playing Animation !");
ani.SetTrigger("EndingAniText");
}
IEnumerator ChangeLevel()
{
yield return new WaitForSeconds(20f);
loadScene.allowSceneActivation = true;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Advertisements;
public class AdController1 : MonoBehaviour, IUnityAdsListener
{
private string store_id = "3983069";
private string video_ad = "video";
private string rewarded_video_ad = "rewardedVideo";
// Start is called before the first frame update
void Start()
{
Advertisement.AddListener(this);
Advertisement.Initialize(store_id, true);
}
// Update is called once per frame
void Update()
{
}
public void ShowAds()
{
if (Advertisement.IsReady(video_ad))
{
Advertisement.Show(video_ad);
}
else
{
Debug.Log("Rewarded video is not ready at the moment! Please try again later!");
}
}
void IUnityAdsListener.OnUnityAdsReady(string placementId)
{
//throw new System.NotImplementedException();
}
void IUnityAdsListener.OnUnityAdsDidError(string message)
{
//throw new System.NotImplementedException();
}
void IUnityAdsListener.OnUnityAdsDidStart(string placementId)
{
///throw new System.NotImplementedException();
}
void IUnityAdsListener.OnUnityAdsDidFinish(string placementId, ShowResult showResult)
{
//throw new System.NotImplementedException();
switch (showResult)
{
case ShowResult.Failed:
break;
case ShowResult.Skipped:
break;
case ShowResult.Finished:
if(placementId == rewarded_video_ad)
{
}
break;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveSlightly : MonoBehaviour
{
public float speed = 2f;
private void FixedUpdate()
{
transform.Translate(Vector2.right * Time.fixedDeltaTime * speed);
}
}
|
40374044ed02c52a14c139d2ca58b744d06a373e
|
[
"Markdown",
"C#"
] | 32
|
C#
|
arnav444a/Q2
|
939fa3be449d9365196b693154ac81f483f64e0f
|
fdd892bbed57add2542e684bd0e6090dd3d07fb5
|
refs/heads/main
|
<file_sep> var array = ["raul" , "andrea" , "mauro", "francesco", "alessandro", "matteo", "martino", "mirko",];
var name = prompt("inserire il tuo cognome");
array.push(name);
array.sort();
console.log(array);
for (var j = 0; j < array.length; j++) {
var elem = array[j];
if (elem == name) {
console.log("Posizione umana di " + name +": " + (j+1));
|
4893199ea60be08cdbd133b0d7e380826cb57e62
|
[
"JavaScript"
] | 1
|
JavaScript
|
Raul-Masnada/js-lista-cognomi
|
0628fa036051f5007b52321bf807f0b3f24ca201
|
c90c26bdb7f4ad564554a027f4daf2ce59075142
|
refs/heads/master
|
<file_sep>import javax.swing.*;
import java.awt.*;
public class Renderer {
public void paintComponent(Graphics g){
Game.game.repaint();
}
}
<file_sep>import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class Screen extends JPanel { //zeichnet den Screen = Map
int x = 0, y = 0, velX = 2, velY = velX;
int xZwei = 1080, yZwei = 0, velXZwei = velX, velYZwei = velXZwei;
int xDrei = 0, yDrei = 740, velXDrei = velX, velYDrei = velXDrei;
int xVier = 1080, yVier = 740, velXVier = velX, velYVier = velXVier;
int x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,x6,y6,x7,y7,x8,y8,x9,y9,x10,y10,x11,y11;
Random random;
int max = 1000;
int maxY = 1000;
public void paintComponent(Graphics g) {
setBackground(Color.GRAY);
//g.setColor(Color.MAGENTA);
//g.fillRect(0,0,10000,10000);
/*g.setColor(Color.YELLOW);
g.drawLine(x1,y1,x2,y2);
g.setColor(Color.GREEN);
g.fillRect(x3,y3,x4,y4);
g.setColor(Color.CYAN);
g.fillOval(x5,y5,x6,y6);
g.setColor(Color.RED);
g.fillArc(x7,y7,x8,y8,x9,x9);
g.setColor(Color.ORANGE);
g.fillRect(x10,y10,x11,y11);*/
random = new Random(); //just4fun
int randomNumX = random.nextInt(max);
int randomNumY = random.nextInt(maxY);
int randomNumX2 = random.nextInt(max);
int randomNumY2 = random.nextInt(maxY);
int randomNumX3 = random.nextInt(max);
int randomNumY3 = random.nextInt(maxY);
int randomNumX4 = random.nextInt(max);
int randomNumY4 = random.nextInt(maxY);
int randomNumX5 = random.nextInt(max);
int randomNumY5 = random.nextInt(maxY);
int randomNumX6 = random.nextInt(max);
int randomNumY6 = random.nextInt(maxY);
int randomNumX7 = random.nextInt(max);
int randomNumY7 = random.nextInt(maxY);
int randomNumX8 = random.nextInt(max);
int randomNumY8 = random.nextInt(maxY);
int randomNumX9 = random.nextInt(max);
int randomNumY9 = random.nextInt(maxY);
int randomNumX10 = random.nextInt(max);
int randomNumY10 = random.nextInt(maxY);
int randomNumX11 = random.nextInt(max);
int randomNumY11 = random.nextInt(maxY);
x1 = randomNumX;
y1 = randomNumY;
x2 = randomNumX2;
y2 = randomNumY2;
x3 = randomNumX3;
y3 = randomNumY3;
x4 = randomNumX4;
y4 = randomNumY4;
x5 = randomNumX5;
y5 = randomNumY5;
x6 = randomNumX6;
y6 = randomNumY6;
x7 = randomNumX7;
y7 = randomNumY7;
x8 = randomNumX8;
y8 = randomNumY8;
x9 = randomNumX9;
y9 = randomNumY9;
x10 = randomNumX10;
y10 = randomNumY10;
x11 = randomNumX11;
y11 = randomNumY11;
g.setColor(Color.BLUE);
g.fillRect(x,y,200,200);
if (x < 0 || x > 1080) { //just4fun
velX = -velX ; }
if (y < 0 || y > 740) {
velY = -velY ; }
x += velX;
y += velY;
g.setColor(Color.BLUE);
g.fillRect(xZwei,yZwei,200,200);
if (xZwei < 0 || xZwei > 1080) { //just4fun
velXZwei = -velXZwei ; }
if (y < 0 || y > 740) {
velYZwei = -velYZwei ; }
xZwei += velXZwei;
yZwei += velYZwei;
g.setColor(Color.BLUE);
g.fillRect(xDrei,yDrei,200,200);
if (xDrei < 0 || xDrei > 1080) { //just4fun
velXDrei = -velXDrei ; }
if (yDrei < 0 || yDrei > 740) {
velYDrei = -velYDrei ; }
xDrei += velXDrei;
yDrei += velYDrei;
g.setColor(Color.BLUE);
g.fillRect(xVier,yVier,200,200);
if (xVier < 0 || xVier > 1080) { //just4fun
velXVier = -velXVier ; }
if (yVier < 0 || yVier > 740) {
velYVier = -velYVier ; }
xVier += velXVier;
yVier += velYVier;
g.setColor(Color.MAGENTA);
g.fillRect(100,100,100,100);
repaint();
}
}
<file_sep>import javax.swing.*;
import java.awt.*;
public class Mainframe extends JFrame { //macht den Frame und fügt dem Frame alle Komponenten des Spiels zu
public Screen screen;
public Player player;
public Game game;
public JLayeredPane jLayeredPane;
public Mainframe(int width, int height) {
super("JumpAndRun");
setSize(width, height);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
jLayeredPane = new JLayeredPane();
JPanel master = new JPanel(new CardLayout());
screen = new Screen();
add(screen);
//player = new Player();
//add(player);
setVisible(true);
setFocusable(true); //für Keylisteners
}
}
<file_sep>import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
public class Game extends JPanel implements ActionListener { //initialisiert das Spiel + ersetzt Klasse Mainboard
public final int WIDTH = 1280;
public final int HEIGHT = 940;
private boolean running = false;
public int x = 2, y = 3,width = 20, height = 20;
public int velX = 500;
public int velY = 500;
public static Game game;
public Mainframe mainframe;
public Screen screen;
public Random random;
public Rectangle object;
public Renderer renderer;
public Player player;
public Game player1;
public Game() {
mainframe = new Mainframe(WIDTH,HEIGHT);
player = new Player();
mainframe.add(player);
movePlayer();
//object = new Rectangle(WIDTH/2, HEIGHT/2,100,100);
//run();
mainframe.setVisible(true);
}
public void start() {
running = true;
}
public void stop() {
System.exit(1);
}
public void run() { //"game loop"
long lastTime = System.nanoTime();
double fps = 60.0;
double ns = 1000000000.0;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
start();
//wenn spiel läuft soll die position der objekte und die map aktualisiert werden, falls tod das spiel beenden
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 0) {
update();
delta--;
}
if(running)
render();
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
if (!running) {
stop();
}
}
private void update() { //aktualisiert das spiel
if (WIDTH == 2734321/* wenn spieler tot*/) {
running = false;
}
}
private void render() {
}
public void paintComponent(Graphics g) {
g.setColor(Color.CYAN);
g.fillRect(0,0,WIDTH,HEIGHT);
g.setColor(Color.BLACK);
g.fillRect(x,y,width,height);
}
public void actionPerformed(ActionEvent e) {
player.x = 200;
player.y = 200;
if (player.x < 0 || player.x > WIDTH) {
velX = -velX;
}
if (player.y < 0 || player.y > HEIGHT) {
velY = -velY;
}
player.x += 2;
player.y += 2;
}
public void keyListener(KeyEvent keyEvent) {
int test = 0;
System.out.println(test);
if(keyEvent.getKeyCode() == KeyEvent.VK_W) {
test = 1;
System.out.println(test);
}
}
public void movePlayer() {
if (player.x < 0 || player.x > WIDTH) {
velX = -velX;
}
if (player.y < 0 || player.y > HEIGHT) {
velY = -velY;
}
player.x += velX;
player.y += velY;
}
public static void main(String[] args) {
game = new Game();
}
}
|
f84de074f809347c06fe63c55a93a899b9e61b59
|
[
"Java"
] | 4
|
Java
|
LFG-Software/PhiPi-PooPoo
|
d2abdbb13e38e9dc3b18be3552bf4879bbfffe88
|
0d552a185d0c505d219b875a098a312954aec70d
|
refs/heads/master
|
<file_sep># Code-material-for-colour-sonification-device
Code materials for colour sonification interactive device, which is the assignment of Interfacing for Audio and Music module.
Hello everyone my name is <NAME> and welcome to my code materials for colour sonification device.
For Python code part, please downlaod Colour Sonification.py
For user interface and sonification patch, please download User Interface.pd.
For full detail of my device, please visit "makemyaudio.design.blog"
<file_sep># Write your code here :-)
from microbit import *
import math
# Initialise all the necessary sensor variables.
i2c.write(0x29, b'\x81\xF6', repeat=False) # Set integrationtime to 24ms.
i2c.write(0x29, b'\x8F\x00', repeat=False) # Set gain of the sensor to 1X.
i2c.write(0x29, b'\x80\x01', repeat=False) # Turn the sensor on.
i2c.write(0x29, b'\x80\x03', repeat=False) # Activate the ADC.
###########################################
# Function to send MIDI data through cable (Transmission the data through pin0)
def Start():
uart.init(baudrate=31250, bits=8, parity=None, stop=1, tx=pin0)
###########################################
""" Function to convert raw data (RGB) to Kelvin (function licensed by MIT)
Function was taken from
https://github.com/adafruit/Adafruit_Python_TCS34725/blob/master/Adafruit_TCS34725/TCS34725.py """
def calculate_color_temperature(r, g, b):
"""Converts the raw R/G/B values to color temperature in degrees Kelvin."""
# 1. Map RGB values to their XYZ counterparts.
# Based on 6500K fluorescent, 3000K fluorescent
# and 60W incandescent values for a wide range.
# Note: Y = Illuminance or lux
X = (-0.14282 * r) + (1.54924 * g) + (-0.95641 * b)
Y = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b)
Z = (-0.68202 * r) + (0.77073 * g) + (0.56332 * b)
# Check for divide by 0 (total darkness) and return None.
if (X + Y + Z) == 0:
return None
# 2. Calculate the chromaticity co-ordinates
xc = (X) / (X + Y + Z)
yc = (Y) / (X + Y + Z)
# Check for divide by 0 again and return None.
if (0.1858 - yc) == 0:
return None
# 3. Use McCamy's formula to determine the CCT
n = (xc - 0.3320) / (0.1858 - yc)
# Calculate the final CCT
cct = (449.0 * (n ** 3.0)) + (3525.0 * (n ** 2.0)) + (6823.3 * n) + 5520.33
return int(cct)
###########################################
# Declare a function of MIDI Control Change (CC) event.
def midiControlChange(chan, n, value):
MIDI_CC = 0xB0
if chan > 15:
return
if n > 127:
return
if value > 127:
return
msg = bytes([MIDI_CC | chan, n, value])
uart.write(msg)
###########################################
Start()
last_ligh = 0 # Initialise a variable with initial value for light sensor.
last_pot = 0 # Innitialise a variable with initial value for potentiometer.
last_tem = 0 # Initialise a variable with initial value for RGB sensor.
while True:
i2c.write(0x29, b'\x96', repeat=False) # Point to red channel register.
rr = i2c.read(0x29, 1, repeat=False) # Read one byte from red channel.
i2c.write(0x29, b'\x98', repeat=False) # Point to green channel register.
gg = i2c.read(0x29, 1, repeat=False) # Read one byte from green channel.
i2c.write(0x29, b'\x9A', repeat=False) # Point to blue channel register.
bb = i2c.read(0x29, 1, repeat=False) # Read one byte from blue channel.
# Once we get the raw data stored in rr, gg, bb variables, send them to function.
# Send RGB raw data [8-bit (0-255)] to the converter function in order to
# convert them into degrees Kelvin.
temp = calculate_color_temperature(float(rr[0]), float(gg[0]), float(bb[0]))
###########################################
# Scale the degrees Kelvin value to a number between 0 and 127 and send its value through MIDI CC event.
if last_tem != temp: # Compare the current value with the last reading.
temper = math.floor(math.fabs((temp + 40000) / 80000) * 127)
midiControlChange(0, 24, temper)
last_tem = temp # Set the last reading variable to the value of the current reading.
# Scale the value from potentiometer to a number between 0 and 127 and send its value through MIDI CC event.
pot = pin2.read_analog() # Read the potentiometer value from pin2
if last_pot != pot:
velocity = math.floor(pot / 1024 * 127)
midiControlChange(0, 23, velocity)
last_pot = pot # Set the last reading variable to the value of the current reading.
# Scale the value from light sensor to a number between 0 and 127 and send its value through MIDI CC event.
current_ligh = display.read_light_level() # Read the light level value.
if current_ligh != last_ligh:
mod_y = math.floor(current_ligh / 255 * 127)
midiControlChange(0, 22, mod_y)
last_ligh = current_ligh # Set the last reading variable to the value of the current reading.
sleep(40) # Sleep for 40ms and repeat the while loop
|
e7b3d7579c555a7560fb689779af871e75a21ef0
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
PavChu/Code-material-for-colour-sonification
|
061cc95ae1ed472f7c31ccd6d1305615895e480b
|
804eae96e70ba3a0890e6f7095422b5690db49fc
|
refs/heads/master
|
<file_sep>
var y="";
function rec1(){
var score= document.getElementById("t1");
y=score.selectedIndex;
if(y==2||y==3){
pro();}
}
function rec2(){
var score= document.getElementById("t2");
y=score.selectedIndex;
if(y==2||y==3){
pro();}
}
function rec3(){
var score= document.getElementById("t3");
y=score.selectedIndex;
if(y==2||y==3){
pro();}
}
function rec4(){
var score= document.getElementById("t4");
y=score.selectedIndex;
if(y==2||y==3){
pro();}
}
function pro(){
var x=prompt("请输入您的原因:");
alert("谢谢您!!我们会及时改进!");
}
|
a84fcbd39852318a319d97c3c616372bfff03063
|
[
"JavaScript"
] | 1
|
JavaScript
|
CChuying/bus
|
43347ceefa6769c9684f2c7b95b525d8762a7e84
|
0183c03080f2a4ab6950e14f2c5d8904d0c29f10
|
refs/heads/master
|
<repo_name>qinbin52qiul/wx-pro<file_sep>/pages/detail/detail.js
// pages/detail.js
//获取应用实例,才能调用全局变量
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
iskebi: false,
iszhan: false,
isqiao: false,
isgeli: false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
var title = wx.getStorageSync('titleName');
console.log(title);
if (title == '科比·布莱恩特') {
this.setData({ iskebi: true });
} else if (title == '勒布朗·詹姆斯') {
this.setData({ iszhan: true });
} else if (title == '迈克尔·乔丹') {
this.setData({ isqiao: true });
} else {
this.setData({ isgeli: true });
}
},
})
|
0f41b1a8e93a4a5cde4ad10ca2ca86d9a39049fc
|
[
"JavaScript"
] | 1
|
JavaScript
|
qinbin52qiul/wx-pro
|
007d71a84bee6d4c426af1ade3e75ab10afda173
|
d1a50769a22bb928119beb2c8a2c8137fb824965
|
refs/heads/master
|
<file_sep>import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from WorldCup import *
class MainWindow(QMainWindow):
""" This is the class for the main window of the world cup python statistics api"""
def __init__(self):
super().__init__()
self.resize(400,400)
self.setWindowTitle("PyCup Statistics")
#attributes
# instantiate the world cup class
self.wc = WorldCup()
#create the stacked layout
self.stacked_layout = QStackedLayout()
#call to layouts
self.create_initial_layout()
self.upcoming_games_layout()
self.current_games_layout()
self.previous_games_layout()
self.widget = QWidget()
self.widget.setLayout(self.stacked_layout)
#set the central widget
self.setCentralWidget(self.widget)
#switch back to the initial layout home page
def back_button_switch(self):
self.stacked_layout.setCurrentIndex(0)
def current_games_switch(self):
self.stacked_layout.setCurrentIndex(2)
def upcoming_games_switch(self):
self.stacked_layout.setCurrentIndex(1)
def previous_games_switch(self):
self.stacked_layout.setCurrentIndex(3)
def match_stats_layout(self, match_id):
#vertical layout
stats = self.wc.getMatchStats(match_id)
team1 = self.wc.getTeam(stats['homeTeamId'])
team2 = self.wc.getTeam(stats['awayTeamId'])
match_title = team1['name'] + 'VS' + team2['name']
self.gameTitle = QLabel(match_title)
self.mainVerticalLayout = QVBoxLayout()
#titleWidget
#get the current games
self.matchStatsData = self.wc.getMatchStats(match_id)
self.mainVerticalLayout.addWidget(self.gameTitle)
self.matchStatsWidget = QWidget()
self.matchStatsWidget.setLayout(self.mainVerticalLayout)
#add the widget to the stacked layout
#has the stack index of ============ 1
self.stacked_layout.addWidget(self.matchStatsWidget)
#button connections
self.backPushButton.clicked.connect(self.back_button_switch)
def create_initial_layout(self):
#vertical layout
self.initialVerticalLayout = QVBoxLayout()
#buttons
self.upcomingGamesPushButton = QPushButton("Upcoming Games")
self.currentGamesPushButton = QPushButton("Current Games")
self.previousGamesPushButton = QPushButton("Previous Games")
self.initialVerticalLayout.addWidget(self.previousGamesPushButton)
self.initialVerticalLayout.addWidget(self.currentGamesPushButton)
self.initialVerticalLayout.addWidget(self.upcomingGamesPushButton)
#new widget
self.initialWidget = QWidget()
self.initialWidget.setLayout(self.initialVerticalLayout)
self.setCentralWidget(self.initialWidget)
#add the widget to the stacked layout
#has the stack index of ========= 0
self.stacked_layout.addWidget(self.initialWidget)
#button connections for initiallayout
self.upcomingGamesPushButton.clicked.connect(self.upcoming_games_switch)
self.currentGamesPushButton.clicked.connect(self.current_games_switch)
self.previousGamesPushButton.clicked.connect(self.previous_games_switch)
def previous_games_layout(self):
#vertical layout
self.mainVerticalLayout = QVBoxLayout()
#titleWidget
self.titleLayout = QHBoxLayout()
self.titleLabel = QLabel("Previous Games")
self.backPushButton = QPushButton("Back")
spacer = QSpacerItem(60,40,QSizePolicy.Minimum,QSizePolicy.Expanding)
self.titleLabel.setStyleSheet("font-size: 18pt; font-family: Courier;")
#self.titleLabel.setStyleSheet("text-align: center;")
self.titleLayout.addWidget(self.backPushButton)
self.titleLayout.addItem(spacer)
self.titleLayout.addWidget(self.titleLabel)
self.titleWidget = QWidget()
self.titleWidget.setLayout(self.titleLayout)
self.mainVerticalLayout.addWidget(self.titleWidget)
#get the current games
self.previousGames = self.wc.getPreviousGames()
for game in self.previousGames[-5:-1]:
#create horizontal layout for each game
self.hLayout = QHBoxLayout()
#QWidgets components
self.homeTeam = self.wc.getTeam(game["homeTeamId"])
self.awayTeam = self.wc.getTeam(game["awayTeamId"])
#labels and buttons
self.homeTeamLabel = QLabel(self.homeTeam["name"])
self.homeTeamLabel.setStyleSheet("qproperty-alignment: AlignCenter;")
self.awayTeamLabel = QLabel(self.awayTeam["name"])
self.awayTeamLabel.setStyleSheet("qproperty-alignment: AlignCenter;")
self.vsLabel = QLabel("VS")
self.vsLabel.setStyleSheet("qproperty-alignment: AlignCenter;")
self.viewGameButton = QPushButton("Stats")
spacer = QSpacerItem(60,40,QSizePolicy.Minimum,QSizePolicy.Expanding)
#add QLabels to the horizontal layout
self.hLayout.addWidget(self.homeTeamLabel)
self.hLayout.addWidget(self.vsLabel)
self.hLayout.addWidget(self.awayTeamLabel)
self.hLayout.addItem(spacer)
self.hLayout.addWidget(self.viewGameButton)
#new QWidget
self.matchWidget = QWidget()
self.matchWidget.setLayout(self.hLayout)
self.mainVerticalLayout.addWidget(self.matchWidget)
#main Widget
self.previousGamesWidget = QWidget()
self.previousGamesWidget.setLayout(self.mainVerticalLayout)
#add the widget to the stacked layout
#has the stack index of ============ 1
self.stacked_layout.addWidget(self.previousGamesWidget)
#button connections
self.backPushButton.clicked.connect(self.back_button_switch)
def current_games_layout(self):
#vertical layout
self.mainVerticalLayout = QVBoxLayout()
#titleWidget
self.titleLayout = QHBoxLayout()
self.titleLabel = QLabel("Current Games")
self.backPushButton = QPushButton("Back")
spacer = QSpacerItem(60,40,QSizePolicy.Minimum,QSizePolicy.Expanding)
self.titleLabel.setStyleSheet("font-size: 18pt; font-family: Courier;")
#self.titleLabel.setStyleSheet("text-align: center;")
self.titleLayout.addWidget(self.backPushButton)
self.titleLayout.addItem(spacer)
self.titleLayout.addWidget(self.titleLabel)
self.titleWidget = QWidget()
self.titleWidget.setLayout(self.titleLayout)
self.mainVerticalLayout.addWidget(self.titleWidget)
#get the current games
self.currentGames = self.wc.getCurrentGames()
for game in self.currentGames:
#create horizontal layout for each game
self.hLayout = QHBoxLayout()
#QWidgets components
self.homeTeam = self.wc.getTeam(game["homeTeamId"])
self.awayTeam = self.wc.getTeam(game["awayTeamId"])
#labels and buttons
self.homeTeamLabel = QLabel(self.homeTeam["name"])
self.homeTeamLabel.setStyleSheet("qproperty-alignment: AlignCenter;")
self.awayTeamLabel = QLabel(self.awayTeam["name"])
self.awayTeamLabel.setStyleSheet("qproperty-alignment: AlignCenter;")
self.vsLabel = QLabel("VS")
self.vsLabel.setStyleSheet("qproperty-alignment: AlignCenter;")
self.viewGameButton = QPushButton("Stats")
spacer = QSpacerItem(60,40,QSizePolicy.Minimum,QSizePolicy.Expanding)
#add QLabels to the horizontal layout
self.hLayout.addWidget(self.homeTeamLabel)
self.hLayout.addWidget(self.vsLabel)
self.hLayout.addWidget(self.awayTeamLabel)
self.hLayout.addItem(spacer)
self.hLayout.addWidget(self.viewGameButton)
#new QWidget
self.matchWidget = QWidget()
self.matchWidget.setLayout(self.hLayout)
self.mainVerticalLayout.addWidget(self.matchWidget)
#main Widget
self.currentGamesWidget = QWidget()
self.currentGamesWidget.setLayout(self.mainVerticalLayout)
#add the widget to the stacked layout
#has the stack index of ============ 2
self.stacked_layout.addWidget(self.currentGamesWidget)
#button connections
self.backPushButton.clicked.connect(self.back_button_switch)
def upcoming_games_layout(self):
#vertical layout
self.mainVerticalLayout = QVBoxLayout()
#titleWidget
self.titleLayout = QHBoxLayout()
self.titleLabel = QLabel("Upcoming Games")
self.backPushButton = QPushButton("Back")
spacer = QSpacerItem(60,40,QSizePolicy.Minimum,QSizePolicy.Expanding)
self.titleLabel.setStyleSheet("font-size: 18pt; font-family: Courier;")
#self.titleLabel.setStyleSheet("text-align: center;")
self.titleLayout.addWidget(self.backPushButton)
self.titleLayout.addItem(spacer)
self.titleLayout.addWidget(self.titleLabel)
self.titleWidget = QWidget()
self.titleWidget.setLayout(self.titleLayout)
self.mainVerticalLayout.addWidget(self.titleWidget)
#get the current games
self.upcomingGames = self.wc.getUpcomingGames()
for game in self.upcomingGames:
#create horizontal layout for each game
self.hLayout = QHBoxLayout()
#QWidgets components
self.homeTeam = self.wc.getTeam(game["homeTeamId"])
self.awayTeam = self.wc.getTeam(game["awayTeamId"])
#labels and buttons
self.homeTeamLabel = QLabel(self.homeTeam["name"])
self.homeTeamLabel.setStyleSheet("qproperty-alignment: AlignCenter;")
self.awayTeamLabel = QLabel(self.awayTeam["name"])
self.awayTeamLabel.setStyleSheet("qproperty-alignment: AlignCenter;")
self.vsLabel = QLabel("VS")
self.vsLabel.setStyleSheet("qproperty-alignment: AlignCenter;")
self.viewGameButton = QPushButton("Stats")
spacer = QSpacerItem(60,40,QSizePolicy.Minimum,QSizePolicy.Expanding)
#add QLabels to the horizontal layout
self.hLayout.addWidget(self.homeTeamLabel)
self.hLayout.addWidget(self.vsLabel)
self.hLayout.addWidget(self.awayTeamLabel)
self.hLayout.addItem(spacer)
self.hLayout.addWidget(self.viewGameButton)
#new QWidget
self.matchWidget = QWidget()
self.matchWidget.setLayout(self.hLayout)
self.mainVerticalLayout.addWidget(self.matchWidget)
#main Widget
self.upcomingGamesWidget = QWidget()
self.upcomingGamesWidget.setLayout(self.mainVerticalLayout)
#add the widget to the stacked layout
#has the stack index of ============ 1
self.stacked_layout.addWidget(self.upcomingGamesWidget)
#button connections
self.backPushButton.clicked.connect(self.back_button_switch)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
window.raise_()
app.exec_()
<file_sep>import urllib.request, json
class WorldCup:
""" This is a python3 class which interfaces with kimono world cup 2014 api. Can generate stats and predict games"""
def __init__(self):
self.upcoming_games = []
self.api_key = "<KEY>"
def getMatchStats(self, match_id):
response = urllib.request.urlopen("http://worldcup.kimonolabs.com/api/matches?sort=status&fields=homeScore,awayScore,currentGameMinute,startTime,status,venue,group,awayTeamId,homeTeamId,id,type&apikey={0}".format(self.api_key))
content = response.read()
data = json.loads(content.decode('utf8'))
match_stats = []
for each in data:
each = dict(each)
if each['id'] == match_id:
match_stats.append(each)
return match_stats
def getMatchTeamStats(self,match_id):
response = urllib.request.urlopen("http://worldcup.kimonolabs.com/api/matches?sort=status&fields=homeScore,awayScore,currentGameMinute,startTime,status,venue,group,awayTeamId,homeTeamId,id,type&apikey={0}".format(self.api_key))
content = response.read()
data = json.loads(content.decode('utf8'))
match_stats = []
for each in data:
each = dict(each)
if each['id'] == match_id:
homeTeamId = each['homeTeamId']
awayTeamId = each['awayTeamId']
match_stats.append(self.getTeam(homeTeamId))
match_stats.append(self.getTeam(awayTeamId))
return match_stats
def getUpcomingGames(self):
response = urllib.request.urlopen("http://worldcup.kimonolabs.com/api/matches?sort=status&fields=homeScore,awayScore,currentGameMinute,startTime,status,venue,group,awayTeamId,homeTeamId,id,type&apikey={0}".format(self.api_key))
content = response.read()
data = json.loads(content.decode('utf8'))
game_list = []
for each in data:
each = dict(each)
if each['status'] == 'Pre-game':
game_list.append(each)
return game_list
def getCurrentGames(self):
response = urllib.request.urlopen("http://worldcup.kimonolabs.com/api/matches?sort=status&fields=homeScore,awayScore,currentGameMinute,startTime,status,venue,group,awayTeamId,homeTeamId,id,type&apikey={0}".format(self.api_key))
content = response.read()
data = json.loads(content.decode('utf8'))
game_list = []
for each in data:
each = dict(each)
if each['status'] == 'In-progress':
game_list.append(each)
return game_list
def getPreviousGames(self):
response = urllib.request.urlopen("http://worldcup.kimonolabs.com/api/matches?sort=status&fields=homeScore,awayScore,currentGameMinute,startTime,status,venue,group,awayTeamId,homeTeamId,id,type&apikey={0}".format(self.api_key))
content = response.read()
data = json.loads(content.decode('utf8'))
game_list = []
for each in data:
each = dict(each)
if each['status'] == 'Final':
game_list.append(each)
return game_list
def getTeam(self, teamId):
response = urllib.request.urlopen("http://worldcup.kimonolabs.com/api/teams/{0}?apikey={1}".format(teamId,self.api_key))
content = response.read()
data = json.loads(content.decode('utf8'))
return data
if __name__ == "__main__":
wc = WorldCup()
games = wc.getGames()
print(games)
<file_sep>WorldCupPy
==========
This is the WorldCupPy Football track python3 and PyQt4 Application
|
146c2806b3775c7f25ae45c3c0ece29b69afc4d7
|
[
"Markdown",
"Python"
] | 3
|
Python
|
kylekirkby/WorldCupPy
|
a22876da3cc0c3bf5c2bce67aabf17142c8b95cf
|
06d6b11576270f98dd4907ffc635ceb34bb0723f
|
refs/heads/master
|
<file_sep>package com.example.flutter_example05
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
|
ef33ef2e3dd030d3e31e5893389cb092fb1a6901
|
[
"Kotlin"
] | 1
|
Kotlin
|
NainAcero/flutter_clean-architect
|
3d6f3f7ad652e5952bcc9b0563b43535235b43d6
|
fecb43519e326ad37109855a6c4afda20ebd98b0
|
refs/heads/master
|
<repo_name>aabadp02/SolitarioSwing<file_sep>/README.md
# SolitarioSwing
Clásico juego del solitario hecho en java con swing.
Este fue el primer programa grande que hice en mi vida. Fue un trabajo para
Programación II. El código es infernal. Mal organizado, mal escrito y poco eficiente,
lleno de redundancias y de código repetido. No obstante era un proyecto bastante grande
teniendo en cuenta el poco tiempo que tuvimos para hacerlo y me siento orgulloso de haberlo
terminado. Conseguí arreglar casi todos los bugs, pero hay uno cuando estás llegando al
final de la partida que con conseguí localizar. Puede que cuando tenga tiempo remasterice el
proyecto.
<file_sep>/src/solitarioswing/SolitarioSwing.java
package solitarioswing;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Random;
import java.util.stream.IntStream;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
class SolitarioSwing extends JFrame // Creacion de la ventana que aparecerá al compilar
{
JLayeredPane panel = new JLayeredPane(); //Utilizamos JLayeredPane porque vamos a necesitar que los componentes puedan estar en diferentes dimensiones y que se puedan colocar unos sobre otros
Carta[] baraja = new Carta[52]; //Aquí guardaremos todas las cartas que componen la baraja
Carta[] control = new Carta[52];
int contador = 28;
int limite = 52; //Este contador nos servirá para recorrer el array de numeros aleatorios entre 1 y 40 que será importante para generar las cartas. Lo ponemos a 28 porque ya habremos puesto28 cartas sobre la mesa
MueveCapa mc = new MueveCapa(); //Método que serivirá para poner arriba del todo el componente que hayamos clicado.
AccionBoton ab = new AccionBoton();
int[] numerosAleatorios = IntStream.rangeClosed(0, 51).toArray(); //En este array guardamos los numeros del 1 al 40 y luego será desordenado
int repeticion = 0; //Numero de veces que volveremos a empezar a poner las cartas sobre la pila original
JMenu archivo = new JMenu("Archivo");
JMenu editar = new JMenu("Editar");
JMenu historial = new JMenu("Historial");
JMenu ayuda = new JMenu("Ayuda");
Font obj = new Font("Bahnschrift", Font.BOLD, 14);
JMenuItem nuevo = new JMenuItem("Nuevo");
JMenuItem cargar = new JMenuItem("Cargar");
JMenuItem guardar = new JMenuItem("Guardar");
JMenuItem guardarComo = new JMenuItem("Guardar como");
JMenuItem salir = new JMenuItem("Salir");
JMenuItem deshacer = new JMenuItem("Deshacer");
JMenuItem hacer = new JMenuItem("Hacer");
JMenuItem resolver = new JMenuItem("Resolver");
JMenuItem estadisticas = new JMenuItem("Estadisticas");
JMenuItem fichero = new JMenuItem("Fichero");
JMenuBar jmb = new JMenuBar();
JButton reponer = new JButton("Reponer");
String ficheroDestino = "SaveSolitario.txt";
int decidirFichero = 2;
//Declaracion de todas las pilas donde podrá haber cartas
Pila todasLasCartas = new Pila( -1); //La pila donde pondremos las cartas al salir de la baraja
Pila primeraPila = new Pila(-1);
Pila segundaPila = new Pila(-1);
Pila terceraPila = new Pila(-1);
Pila cuartaPila = new Pila(-1);
Pila quintaPila = new Pila(-1);
Pila sextaPila = new Pila(-1);
Pila septimaPila = new Pila(-1);
//Declaración de las pilas finales con las cartas ordenadas por palos
Pila pilaDeOros = new Pila(0); //Con los números le indicaremos qué palos pueden ir en las pilas.
Pila pilaDeEspadas = new Pila(1);
Pila pilaDeBastos = new Pila(2);
Pila pilaDeCopas = new Pila(3);
int contadorPica = 0;
int contadorTrevol = 0;
int contadorCorazon = 0;
int contadorDiamante = 0;
GeneradorDeCartas cart = new GeneradorDeCartas();
public SolitarioSwing() //Constructor de la clase
{
setBounds(100, 100, 1500, 1080);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("SOLITARIO");
setResizable(false);
int contadorBaraja = 0; //Contador para recorrer el array de la baraja e ir introduciendo en él cada carta.
//Rellenamos el mazo
for(int palo = 0; palo < 4; palo++)
{
for(int numero = 0; numero < 13; numero++)
{
baraja[contadorBaraja] = new Carta(palo, numero, 1);
contadorBaraja++;
}
}
control = baraja;
//desordenando los elementos
Random r = new Random();
for (int i = numerosAleatorios.length; i > 0; i--)
{
int posicion = r.nextInt(i);
int tmp = numerosAleatorios[i-1];
numerosAleatorios[i - 1] = numerosAleatorios[posicion];
numerosAleatorios[posicion] = tmp;
}
//Ponemos el JLabel que servirá de baraja
//Este será el dorso que al clicar generará las cartas.
panel.setPreferredSize(new Dimension(300, 300));
getContentPane().add(panel); //Añadimos el JLayeredPane
Toolkit miPantalla = Toolkit.getDefaultToolkit();
Image logo = miPantalla.getImage(getClass().getResource("/Imagenes/PosibleLogo.jpg"));
setIconImage(logo);
ImageIcon imagenFondo = new ImageIcon(getClass().getResource("/Imagenes/TapeteCartas.jpg")); //Ponemos la imagen de fondo
JLabel imagenDeFondo = new JLabel(imagenFondo);
imagenDeFondo.setOpaque(true);
imagenDeFondo.setBounds(0, 0, 1920, 1080);
panel.add(imagenDeFondo, new Integer(0));
panel.setPosition(imagenDeFondo, 0);
// panel.setBackground(new Color(51, 153, 45));
panel.setOpaque(true);
cart.setOpaque(true); //Añadimos el generador de las cartas.
cart.setBounds(30, 30, 100, 139);
panel.add(cart, new Integer(0));
panel.setPosition(cart, 0);
ImageIcon palo1 = new ImageIcon(getClass().getResource("/Imagenes/puramierda.jpg"));
JLabel imagenPalo1 = new JLabel(palo1);
imagenPalo1.setOpaque(true);
imagenPalo1.setBounds(1057, 30, 100, 139);
panel.add(imagenPalo1, new Integer(0));
panel.setPosition(imagenPalo1, 0);
ImageIcon palo2 = new ImageIcon(getClass().getResource("/Imagenes/puramierda2.jpg"));
JLabel imagenPalo2 = new JLabel(palo2);
imagenPalo2.setOpaque(true);
imagenPalo2.setBounds(1057, 229, 100, 139);
panel.add(imagenPalo2, new Integer(0));
panel.setPosition(imagenPalo2, 0);
ImageIcon palo3 = new ImageIcon(getClass().getResource("/Imagenes/puramierda3.jpg"));
JLabel imagenPalo3 = new JLabel(palo3);
imagenPalo3.setOpaque(true);
imagenPalo3.setBounds(1057, 428, 100, 139);
panel.add(imagenPalo3, new Integer(0));
panel.setPosition(imagenPalo3, 0);
ImageIcon palo4 = new ImageIcon(getClass().getResource("/Imagenes/puramierdaBien.jpg"));
JLabel imagenPalo4 = new JLabel(palo4);
imagenPalo4.setOpaque(true);
imagenPalo4.setBounds(1057, 627, 100, 139);
panel.add(imagenPalo4, new Integer(0));
panel.setPosition(imagenPalo4, 0);
ImageIcon fondoBaraja = new ImageIcon(getClass().getResource("/Imagenes/puramierdaB.jpg"));
JLabel imagenBaraja = new JLabel(fondoBaraja);
reponer.setOpaque(true);
reponer.setBounds(30, 400, 100, 60);
reponer.setBackground(Color.black);
reponer.setForeground(Color.white);
reponer.setFont(obj);
reponer.setFocusPainted(false);
panel.add(reponer, new Integer(0));
panel.setPosition(reponer, 0);
reponer.setVisible(false);
reponer.addActionListener(ab);
imagenBaraja.setOpaque(true);
imagenBaraja.setBounds(30, 200, 100, 139);
panel.add(imagenBaraja, new Integer(0));
panel.setPosition(imagenBaraja, 0);
jmb.setOpaque(true);
jmb.setBounds(0, 0, 1920, 20);
panel.add(jmb, new Integer(0));
panel.setPosition(jmb, 0);
jmb.add(archivo);
jmb.add(editar);
jmb.add(historial);
jmb.add(ayuda);
archivo.add(nuevo);
archivo.add(cargar);
archivo.add(guardar);
archivo.add(guardarComo);
archivo.add(salir);
editar.add(deshacer);
editar.add(hacer);
editar.add(resolver);
historial.add(estadisticas);
historial.add(fichero);
nuevo.addActionListener(ab);
cargar.addActionListener(ab);
guardar.addActionListener(ab);
guardarComo.addActionListener(ab);
salir.addActionListener(ab);
deshacer.addActionListener(ab);
ayuda.addActionListener(ab);
//Ponemos las cartas correspondientes sobre la mesa.
//Pila 7
for(int i = 0; i < 7; i++)
{
if(i != 6)
{
baraja[numerosAleatorios[i]].darLaVuelta();
}
baraja[numerosAleatorios[i]].setOpaque(true);
baraja[numerosAleatorios[i]].setBounds(927, 30 * (i + 1), 100, 139);
panel.add(baraja[numerosAleatorios[i]], new Integer(0));
panel.setPosition(baraja[numerosAleatorios[i]], 1); //Se generará una carta aleatoria en la posicion indicada
baraja[numerosAleatorios[i]].setOrigin(927, 30 * (i + 1)); //Marcaremos dicha posicion como origen de la carta para que vuelva ahí cuando arrastremos y no podamos ponerla en ningún sitio (o en un sitio incorrecto)
panel.moveToFront(baraja[numerosAleatorios[i]]); //Indicaremos que ese será el componente que esté arriba
septimaPila.cartaSiPrincipal(baraja[numerosAleatorios[i]]);
baraja[numerosAleatorios[i]].addMouseListener(mc);
}
for(int i = 7; i < 13; i++)
{
if(i != 12)
{
baraja[numerosAleatorios[i]].darLaVuelta();
}
baraja[numerosAleatorios[i]].setOpaque(true);
baraja[numerosAleatorios[i]].setBounds(797, 30 * (i + 1 - 7), 100, 139);
panel.add(baraja[numerosAleatorios[i]], new Integer(0));
panel.setPosition(baraja[numerosAleatorios[i]], 1); //Se generará una carta aleatoria en la posicion indicada
baraja[numerosAleatorios[i]].setOrigin(797, 30 * (i + 1 - 7)); //Marcaremos dicha posicion como origen de la carta para que vuelva ahí cuando arrastremos y no podamos ponerla en ningún sitio (o en un sitio incorrecto)
panel.moveToFront(baraja[numerosAleatorios[i]]); //Indicaremos que ese será el componente que esté arriba
sextaPila.cartaSiPrincipal(baraja[numerosAleatorios[i]]);
baraja[numerosAleatorios[i]].addMouseListener(mc);
}
for(int i = 13; i < 18; i++)
{
if(i != 17)
{
baraja[numerosAleatorios[i]].darLaVuelta();
}
baraja[numerosAleatorios[i]].setOpaque(true);
baraja[numerosAleatorios[i]].setBounds(667, 30 * (i + 1 - 13), 100, 139);
panel.add(baraja[numerosAleatorios[i]], new Integer(0));
panel.setPosition(baraja[numerosAleatorios[i]], 1); //Se generará una carta aleatoria en la posicion indicada
baraja[numerosAleatorios[i]].setOrigin(667, 30 * (i + 1 - 13)); //Marcaremos dicha posicion como origen de la carta para que vuelva ahí cuando arrastremos y no podamos ponerla en ningún sitio (o en un sitio incorrecto)
panel.moveToFront(baraja[numerosAleatorios[i]]); //Indicaremos que ese será el componente que esté arriba
quintaPila.cartaSiPrincipal(baraja[numerosAleatorios[i]]);
baraja[numerosAleatorios[i]].addMouseListener(mc);
}
for(int i = 18; i < 22; i++)
{
if(i != 21)
{
baraja[numerosAleatorios[i]].darLaVuelta();
}
baraja[numerosAleatorios[i]].setOpaque(true);
baraja[numerosAleatorios[i]].setBounds(537, 30 * (i + 1 - 18), 100, 139);
panel.add(baraja[numerosAleatorios[i]], new Integer(0));
panel.setPosition(baraja[numerosAleatorios[i]], 1); //Se generará una carta aleatoria en la posicion indicada
baraja[numerosAleatorios[i]].setOrigin(537, 30 * (i + 1 - 18)); //Marcaremos dicha posicion como origen de la carta para que vuelva ahí cuando arrastremos y no podamos ponerla en ningún sitio (o en un sitio incorrecto)
panel.moveToFront(baraja[numerosAleatorios[i]]); //Indicaremos que ese será el componente que esté arriba
cuartaPila.cartaSiPrincipal(baraja[numerosAleatorios[i]]);
baraja[numerosAleatorios[i]].addMouseListener(mc);
}
for(int i = 22; i < 25; i++)
{
if(i != 24)
{
baraja[numerosAleatorios[i]].darLaVuelta();
}
baraja[numerosAleatorios[i]].setOpaque(true);
baraja[numerosAleatorios[i]].setBounds(407, 30 * (i + 1 - 22), 100, 139);
panel.add(baraja[numerosAleatorios[i]], new Integer(0));
panel.setPosition(baraja[numerosAleatorios[i]], 1); //Se generará una carta aleatoria en la posicion indicada
baraja[numerosAleatorios[i]].setOrigin(407, 30 * (i + 1 - 22)); //Marcaremos dicha posicion como origen de la carta para que vuelva ahí cuando arrastremos y no podamos ponerla en ningún sitio (o en un sitio incorrecto)
panel.moveToFront(baraja[numerosAleatorios[i]]); //Indicaremos que ese será el componente que esté arriba
terceraPila.cartaSiPrincipal(baraja[numerosAleatorios[i]]);
baraja[numerosAleatorios[i]].addMouseListener(mc);
}
for(int i = 25; i < 27; i++)
{
if(i != 26)
{
baraja[numerosAleatorios[i]].darLaVuelta();
}
baraja[numerosAleatorios[i]].setOpaque(true);
baraja[numerosAleatorios[i]].setBounds(277, 30 * (i + 1 - 25), 100, 139);
panel.add(baraja[numerosAleatorios[i]], new Integer(0));
panel.setPosition(baraja[numerosAleatorios[i]], 1); //Se generará una carta aleatoria en la posicion indicada
baraja[numerosAleatorios[i]].setOrigin(277, 30 * (i + 1 - 25)); //Marcaremos dicha posicion como origen de la carta para que vuelva ahí cuando arrastremos y no podamos ponerla en ningún sitio (o en un sitio incorrecto)
panel.moveToFront(baraja[numerosAleatorios[i]]); //Indicaremos que ese será el componente que esté arriba
segundaPila.cartaSiPrincipal(baraja[numerosAleatorios[i]]);
baraja[numerosAleatorios[i]].addMouseListener(mc);
}
for(int i = 27; i < 28; i++)
{
baraja[numerosAleatorios[i]].setOpaque(true);
baraja[numerosAleatorios[i]].setBounds(157, 30 * (i + 1 - 27), 100, 139);
panel.add(baraja[numerosAleatorios[i]], new Integer(0));
panel.setPosition(baraja[numerosAleatorios[i]], 1); //Se generará una carta aleatoria en la posicion indicada
baraja[numerosAleatorios[i]].setOrigin(157, 30 * (i + 1 - 27)); //Marcaremos dicha posicion como origen de la carta para que vuelva ahí cuando arrastremos y no podamos ponerla en ningún sitio (o en un sitio incorrecto)
panel.moveToFront(baraja[numerosAleatorios[i]]); //Indicaremos que ese será el componente que esté arriba
primeraPila.cartaSiPrincipal(baraja[numerosAleatorios[i]]);
baraja[numerosAleatorios[i]].addMouseListener(mc);
}
setVisible(true);
}
public class Dialog extends JDialog
{
public Dialog()
{
setTitle("Ayuda");
setResizable(false);
setBounds(500, 500, 200, 200);
JTextPane texto = new JTextPane();
texto.setText("Prueba");
texto.setBackground(getContentPane().getBackground());
texto.setEditable(false);
add(texto);
}
}
public void saveData(String fichero)
{
try
{
BufferedWriter bw = new BufferedWriter(new FileWriter(fichero));
//Guardamos lo que haya en el generador de Cartas (pila todasLasCartas) todo lo relacionado
bw.write("" + contador); //Guardamos la posicion del contador
bw.newLine();
bw.write("" + limite); //Guardamos el valor del limite
bw.newLine();
bw.write("" + repeticion);
bw.newLine();
/* if(repeticion == 0)
{
for(int i = contador; i < limite; i++)
{
int posicion = EncuentraCartaBaraja(baraja[i]);
bw.write("" + posicion);
bw.newLine();
}
}*/
bw.write("" + todasLasCartas.numeroCartas());
bw.newLine();
//Le daremos cada carta y su posicion en pila
for(int i = 0; i < todasLasCartas.numeroCartas(); i++)
{
//Llamamos al metodo encuentra carta.
bw.write("" + EncuentraCarta(i, todasLasCartas) ); //Le pasamos la i para que compare cada carta de la pila y un 0 representando la pila "todasLasCartas"
bw.newLine(); // Hemos guardado la posicion que ocupa la carta en baraja[] (para saber qué carta es)
}
//Guardamos lo que hay en la primera pila
bw.write("" + primeraPila.numeroCartas()); //Guardamos el numero de cartas en la pila
bw.newLine();
for(int i = 0; i < primeraPila.numeroCartas(); i++)
{
int posicion = EncuentraCarta(i, primeraPila);
bw.write("" + posicion); //Posicion de la carta en control
bw.newLine();
bw.write("" + control[posicion].getReverso());
bw.newLine();
}
//Guardamos lo que hay en la segunda pila
bw.write("" + segundaPila.numeroCartas());
bw.newLine();
for(int i = 0; i < segundaPila.numeroCartas(); i++)
{
int posicion = EncuentraCarta(i, segundaPila);
bw.write("" + posicion);
bw.newLine();
bw.write("" + control[posicion].getReverso());
bw.newLine();
}
//Guardamos lo que hay en la tercera pila
bw.write("" + terceraPila.numeroCartas());
bw.newLine();
for(int i = 0; i < terceraPila.numeroCartas(); i++)
{
int posicion = EncuentraCarta(i, terceraPila);
bw.write("" + posicion);
bw.newLine();
bw.write("" + control[posicion].getReverso());
bw.newLine();
}
//Guardamos lo que hay en la cuarta pila
bw.write("" + cuartaPila.numeroCartas());
bw.newLine();
for(int i = 0; i < cuartaPila.numeroCartas(); i++)
{
int posicion = EncuentraCarta(i, cuartaPila);
bw.write("" + posicion);
bw.newLine();
bw.write("" + control[posicion].getReverso());
bw.newLine();
}
//Guardamos lo que hay en la quinta pila
bw.write("" + quintaPila.numeroCartas());
bw.newLine();
for(int i = 0; i < quintaPila.numeroCartas(); i++)
{
int posicion = EncuentraCarta(i, quintaPila);
bw.write("" + posicion);
bw.newLine();
bw.write("" + control[posicion].getReverso());
bw.newLine();
}
//Guardamos lo que hay en la sexta pila
bw.write("" + sextaPila.numeroCartas());
bw.newLine();
for(int i = 0; i < sextaPila.numeroCartas(); i++)
{
int posicion = EncuentraCarta(i, sextaPila);
bw.write("" + posicion);
bw.newLine();
bw.write("" + control[posicion].getReverso());
bw.newLine();
}
//Guardamos lo que hay en la septima pila
bw.write("" + septimaPila.numeroCartas());
bw.newLine();
for(int i = 0; i < septimaPila.numeroCartas(); i++)
{
int posicion = EncuentraCarta(i, septimaPila);
bw.write("" + posicion);
bw.newLine();
bw.write("" + control[posicion].getReverso());
bw.newLine();
}
//Guardamos lo que hay en el palo de las picas
bw.write("" + pilaDeOros.numeroCartas());
bw.newLine();
for(int i = 0; i < pilaDeOros.numeroCartas(); i++)
{
int posicion = EncuentraCarta(i, pilaDeOros);
bw.write("" + posicion);
bw.newLine();
bw.write("" + control[posicion].getReverso());
bw.newLine();
}
//Guardamos lo que hay en el palo de los trevoles
bw.write("" + pilaDeEspadas.numeroCartas());
bw.newLine();
for(int i = 0; i < pilaDeEspadas.numeroCartas(); i++)
{
int posicion = EncuentraCarta(i, pilaDeEspadas);
bw.write("" + posicion);
bw.newLine();
bw.write("" + control[posicion].getReverso());
bw.newLine();
}
//Guardamos lo que hay en el palo de los Corazones
bw.write("" + pilaDeBastos.numeroCartas());
bw.newLine();
for(int i = 0; i < pilaDeBastos.numeroCartas(); i++)
{
int posicion = EncuentraCarta(i, pilaDeBastos);
bw.write("" + posicion);
bw.newLine();
bw.write("" + control[posicion].getReverso());
bw.newLine();
}
//Guardamos lo que hayn el el palo de los diamantes
bw.write("" + pilaDeCopas.numeroCartas());
bw.newLine();
for(int i = 0; i < pilaDeCopas.numeroCartas(); i++)
{
int posicion = EncuentraCarta(i, pilaDeCopas);
bw.write("" + posicion);
bw.newLine();
bw.write("" + control[posicion].getReverso());
bw.newLine();
}
bw.close();
}
catch(Exception e)
{
System.out.println("Ha habido un error al guardar partida");
}
}
public void loadData(String fichero)
{
/* for(int i = 0;i < baraja.length; i++)
{
baraja[i] = null;
}*/
todasLasCartas.vaciarPila();
primeraPila.vaciarPila();
segundaPila.vaciarPila();
terceraPila.vaciarPila();
cuartaPila.vaciarPila();
quintaPila.vaciarPila();
sextaPila.vaciarPila();
septimaPila.vaciarPila();
pilaDeOros.vaciarPila();
pilaDeEspadas.vaciarPila();
pilaDeBastos.vaciarPila();
pilaDeCopas.vaciarPila();
int contadorTodasLasCartas = 0;
try
{
BufferedReader br = new BufferedReader(new FileReader(fichero));
contador = Integer.parseInt(br.readLine());
limite = Integer.parseInt(br.readLine());
repeticion = Integer.parseInt(br.readLine());
contadorTodasLasCartas = Integer.parseInt(br.readLine()); //Guardamos el numero de cartas que tendremos en la pila TODASLASCARTAS
//Cargamos las cartas de la pila todasLasCartas
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
posicionCarta = Integer.parseInt(br.readLine());
control[posicionCarta].descubrir();
todasLasCartas.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(30, 200);
panel.moveToFront(control[posicionCarta]);
control[posicionCarta].setOrigin(30, 200);
}
//Cargamos las cartas de la primera pila
contadorTodasLasCartas = 0;
contadorTodasLasCartas = Integer.parseInt(br.readLine());
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
int reverso = 0;
posicionCarta = Integer.parseInt(br.readLine());
reverso = Integer.parseInt(br.readLine());
if(reverso == 0)
{
control[posicionCarta].darLaVuelta();
primeraPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(157, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(157, 30 * (control[posicionCarta].getPosicion() + 1));
}
else
{
control[posicionCarta].descubrir();
primeraPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(157, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(157, 30 * (control[posicionCarta].getPosicion() + 1));
}
}
contadorTodasLasCartas = Integer.parseInt(br.readLine());
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
int reverso = 0;
posicionCarta = Integer.parseInt(br.readLine());
reverso = Integer.parseInt(br.readLine());
if(reverso == 0)
{
control[posicionCarta].darLaVuelta();
segundaPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(277, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(277, 30 * (control[posicionCarta].getPosicion() + 1));
}
else
{
control[posicionCarta].descubrir();
segundaPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(277, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(277, 30 * (control[posicionCarta].getPosicion() + 1));
}
}
contadorTodasLasCartas = Integer.parseInt(br.readLine());
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
int reverso = 0;
posicionCarta = Integer.parseInt(br.readLine());
reverso = Integer.parseInt(br.readLine());
if(reverso == 0)
{
control[posicionCarta].darLaVuelta();
terceraPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(407, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(407, 30 * (control[posicionCarta].getPosicion() + 1));
}
else
{
control[posicionCarta].descubrir();
terceraPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(407, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(407, 30 * (control[posicionCarta].getPosicion() + 1));
}
}
contadorTodasLasCartas = Integer.parseInt(br.readLine());
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
int reverso = 0;
posicionCarta = Integer.parseInt(br.readLine());
reverso = Integer.parseInt(br.readLine());
if(reverso == 0)
{
control[posicionCarta].darLaVuelta();
cuartaPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(537, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(537, 30 * (control[posicionCarta].getPosicion() + 1));
}
else
{
control[posicionCarta].descubrir();
cuartaPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(537, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(537, 30 * (control[posicionCarta].getPosicion() + 1));
}
}
contadorTodasLasCartas = Integer.parseInt(br.readLine());
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
int reverso = 0;
posicionCarta = Integer.parseInt(br.readLine());
reverso = Integer.parseInt(br.readLine());
if(reverso == 0)
{
control[posicionCarta].darLaVuelta();
quintaPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(667, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(667, 30 * (control[posicionCarta].getPosicion() + 1));
}
else
{
control[posicionCarta].descubrir();
quintaPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(667, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(667, 30 * (control[posicionCarta].getPosicion() + 1));
}
}
contadorTodasLasCartas = Integer.parseInt(br.readLine());
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
int reverso = 0;
posicionCarta = Integer.parseInt(br.readLine());
reverso = Integer.parseInt(br.readLine());
if(reverso == 0)
{
control[posicionCarta].darLaVuelta();
sextaPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(797, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(797, 30 * (control[posicionCarta].getPosicion() + 1));
}
else
{
control[posicionCarta].descubrir();
sextaPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(797, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(797, 30 * (control[posicionCarta].getPosicion() + 1));
}
}
contadorTodasLasCartas = Integer.parseInt(br.readLine());
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
int reverso = 0;
posicionCarta = Integer.parseInt(br.readLine());
reverso = Integer.parseInt(br.readLine());
if(reverso == 0)
{
control[posicionCarta].darLaVuelta();
septimaPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(927, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(927, 30 * (control[posicionCarta].getPosicion() + 1));
}
else
{
control[posicionCarta].descubrir();
septimaPila.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(927, 30 * (control[posicionCarta].getPosicion() + 1));
control[posicionCarta].setOrigin(927, 30 * (control[posicionCarta].getPosicion() + 1));
}
}
contadorTodasLasCartas = Integer.parseInt(br.readLine());
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
int reverso = 0;
posicionCarta = Integer.parseInt(br.readLine());
reverso = Integer.parseInt(br.readLine());
if(reverso == 0)
{
control[posicionCarta].darLaVuelta();
pilaDeOros.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(927, 30);
control[posicionCarta].setOrigin(927, 30 );
}
else
{
control[posicionCarta].descubrir();
pilaDeOros.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(927, 30);
control[posicionCarta].setOrigin(927, 30);
}
}
contadorTodasLasCartas = Integer.parseInt(br.readLine());
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
int reverso = 0;
posicionCarta = Integer.parseInt(br.readLine());
reverso = Integer.parseInt(br.readLine());
if(reverso == 0)
{
control[posicionCarta].darLaVuelta();
pilaDeEspadas.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(1057, 229);
control[posicionCarta].setOrigin(1057, 229);
}
else
{
control[posicionCarta].descubrir();
pilaDeEspadas.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(1057, 229);
control[posicionCarta].setOrigin(1057, 229);
}
}
contadorTodasLasCartas = Integer.parseInt(br.readLine());
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
int reverso = 0;
posicionCarta = Integer.parseInt(br.readLine());
reverso = Integer.parseInt(br.readLine());
if(reverso == 0)
{
control[posicionCarta].darLaVuelta();
pilaDeBastos.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(1057, 428);
control[posicionCarta].setOrigin(1057, 428);
}
else
{
control[posicionCarta].descubrir();
pilaDeBastos.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(1057, 428);
control[posicionCarta].setOrigin(1057, 428);
}
}
contadorTodasLasCartas = Integer.parseInt(br.readLine());
for(int i = 0; i < contadorTodasLasCartas; i++)
{
int posicionCarta = 0;
int reverso = 0;
posicionCarta = Integer.parseInt(br.readLine());
reverso = Integer.parseInt(br.readLine());
if(reverso == 0)
{
control[posicionCarta].darLaVuelta();
pilaDeCopas.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(1057, 627);
control[posicionCarta].setOrigin(1057, 627);
}
else
{
control[posicionCarta].descubrir();
pilaDeCopas.cartaSiPrincipal(control[posicionCarta]);
control[posicionCarta].setLocation(1057, 627);
control[posicionCarta].setOrigin(1057, 627);
}
}
br.close();
}
catch(Exception e)
{
System.out.println("Se ha producido un error al cargar la partida");
}
}
class AccionBoton implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == reponer)
{
reponer.setVisible(false);
for(int i = 0; i < limite; i++)
{
baraja[i].setVisible(false);
}
cart.setVisible(true);
}
else if(e.getSource() == guardar)
{
saveData(ficheroDestino);
}
else if(e.getSource() == cargar)
{
loadData(ficheroDestino);
}
else if(e.getSource() == nuevo)
{
new SolitarioSwing();
}
else if(e.getSource() == guardarComo)
{
JButton open = new JButton();
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new java.io.File("."));
fc.setDialogTitle("Nuevo Solitario");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if(fc.showOpenDialog(open) == JFileChooser.APPROVE_OPTION);
ficheroDestino = fc.getSelectedFile().getAbsolutePath();
loadData(ficheroDestino);
}
else if(e.getSource() == salir)
{
System.exit(0);
}
else if(e.getSource() == deshacer)
{
if(decidirFichero == 2)
{
}
else if(decidirFichero % 2 == 0)
{
loadData("Deshacer2.txt");
}
else
{
loadData("Deshacer.txt");
}
}
else if(e.getSource() == ayuda)
{
Dialog textoAyuda = new Dialog();
textoAyuda.setVisible(true);
}
}
}
public int EncuentraCarta(int posicion, Pila pila)
{
int posicionControl = 2;
for(int i = 0; i < 52; i++)
{
if(pila.getPaloPosicion(posicion) == control[i].getPalo())
{
if(pila.getNumeroPosicion(posicion) == control[i].getNumero())
{
posicionControl = i;
break;
}
}
}
return posicionControl;
}
public int EncuentraCartaBaraja(Carta carta)
{
int posicionControl = 0;
for(int i = 0; i < 52; i++)
{
if(carta.getPalo() == control[i].getPalo())
{
if(carta.getNumero() == control[i].getNumero())
{
posicionControl = i;
break;
}
}
}
return posicionControl;
}
class GeneradorDeCartas extends JLabel implements MouseListener
{
public GeneradorDeCartas()
{
ImageIcon helper = new ImageIcon(getClass().getResource("/Imagenes/DorsoDeCarta.jpg"));
setIcon(helper); //Le ponemos una imagen (de un dorso) para saber dónde clicar exactamente
addMouseListener(this); //Lo ponemos como listener del mouse para que detecte los clicks
}
@Override
public void mouseClicked(MouseEvent e) //Cada vez que hagamos click sobre el:
{
if(contador == limite - 1)
{
this.setVisible(false);
reponer.setVisible(true);
contador++;
}
if(contador == limite)
{
contador = 0;
baraja = todasLasCartas.devolverBaraja();
limite = todasLasCartas.numeroCartas();
repeticion++;
}
if(repeticion == 0)
{
baraja[numerosAleatorios[contador]].setOpaque(true);
baraja[numerosAleatorios[contador]].setBounds(30, 200, 100, 139);
panel.add(baraja[numerosAleatorios[contador]], new Integer(0));
panel.setPosition(baraja[numerosAleatorios[contador]], 1); //Se generará una carta aleatoria en la posicion indicada
baraja[numerosAleatorios[contador]].setOrigin(30, 200); //Marcaremos dicha posicion como origen de la carta para que vuelva ahí cuando arrastremos y no podamos ponerla en ningún sitio (o en un sitio incorrecto)
panel.moveToFront(baraja[numerosAleatorios[contador]]); //Indicaremos que ese será el componente que esté arriba
todasLasCartas.cartaSiPrincipal(baraja[numerosAleatorios[contador]]);
baraja[numerosAleatorios[contador]].addMouseListener(mc); //A cada carta le daremos la instruccion de ser el componente que esté arriba cuando cliquemos sobre ella
}
else
{
baraja[contador].setVisible(true);
panel.moveToFront(baraja[contador]);
System.out.println("Hola");
}
System.out.println("contador: " + contador);
contador++; //Aumentamos el contador para seguir avanzando por el array de aleatorios
if(decidirFichero % 2 == 0)
{
saveData("Deshacer2.txt");
}
else
{
saveData("Deshacer.txt");
}
decidirFichero++;
}
@Override
public void mousePressed(MouseEvent e){};@Override public void mouseReleased(MouseEvent e){};@Override public void mouseEntered(MouseEvent e){};@Override public void mouseExited(MouseEvent e){};
}
class MueveCapa implements MouseListener //Esta es la clase que se encarga de poner el componente indicado arriba del todo
{
@Override
public void mousePressed(MouseEvent e)
{
Carta carta = (Carta) e.getSource();
Carta[] cartas = new Carta[52];
int posicionCarta;
int numeroDeCartas;
posicionCarta = carta.getPosicion();
System.out.println("La posicion de la carta es: " + posicionCarta);
numeroDeCartas = carta.getPilaOrigen(carta.getOrigenX(), carta.getOrigenY()).numeroCartas();
if(posicionCarta == numeroDeCartas - 1)
{
panel.moveToFront(carta);
}
else if(carta.getPilaOrigen(carta.getOrigenX(), carta.getOrigenY()) == todasLasCartas)
{
panel.moveToFront(carta);
}
else
{
cartas = carta.getPilaOrigen(carta.getOrigenX(), carta.getOrigenY()).devolverBaraja();
for(int i = posicionCarta; i < numeroDeCartas; i++)
{
panel.moveToFront(cartas[i]);
}
}
}
@Override
public void mouseClicked(MouseEvent e){};@Override public void mouseReleased(MouseEvent e){};@Override public void mouseEntered(MouseEvent e){};@Override public void mouseExited(MouseEvent e){};
}
public class Carta extends JLabel implements MouseMotionListener
{
int palo = 0;
int numero = 0;
int xOrigen = 0; //Estas serán las posiciones que indiquen dónde estará anclada la carta en caso de que la pongamos en un sitio que no sea correcto. Como no podrá ponerse ahí, volverá al origen
int yOrigen = 0;
int posicionEnPila = 0; //También podremos saber en qué posicion de la pila se encuentra la carta
ImageIcon reversoCarta = new ImageIcon(getClass().getResource("/Imagenes/DorsoDeCarta.jpg"));
int reverso = 0;
ImageIcon imagenCarta;
String[][] todaCarta =
{
{"/Imagenes/ace_of_spades2.png", "/Imagenes/2_of_spades.png", "/Imagenes/3_of_spades.png", "/Imagenes/4_of_spades.png", "/Imagenes/5_of_spades.png", "/Imagenes/6_of_spades.png", "/Imagenes/7_of_spades.png", "/Imagenes/8_of_spades.png","/Imagenes/9_of_spades.png","/Imagenes/10_of_spades.png", "/Imagenes/jack_of_spades2.png", "/Imagenes/queen_of_spades2.png", "/Imagenes/king_of_spades2.png"},
{"/Imagenes/ace_of_clubs.png", "/Imagenes/2_of_clubs.png", "/Imagenes/3_of_clubs.png", "/Imagenes/4_of_clubs.png", "/Imagenes/5_of_clubs.png", "/Imagenes/6_of_clubs.png", "/Imagenes/7_of_clubs.png", "/Imagenes/8_of_clubs.png", "/Imagenes/9_of_clubs.png", "/Imagenes/10_of_clubs.png", "/Imagenes/jack_of_clubs2.png", "/Imagenes/queen_of_clubs2.png", "/Imagenes/king_of_clubs2.png"},
{"/Imagenes/ace_of_hearts.png", "/Imagenes/2_of_hearts.png", "/Imagenes/3_of_hearts.png", "/Imagenes/4_of_hearts.png", "/Imagenes/5_of_hearts.png", "/Imagenes/6_of_hearts.png", "/Imagenes/7_of_hearts.png", "/Imagenes/8_of_hearts.png", "/Imagenes/9_of_hearts.png", "/Imagenes/10_of_hearts.png", "/Imagenes/jack_of_hearts2.png", "/Imagenes/queen_of_hearts2.png", "/Imagenes/king_of_hearts2.png"},
{"/Imagenes/ace_of_diamonds.png", "/Imagenes/2_of_diamonds.png", "/Imagenes/3_of_diamonds.png", "/Imagenes/4_of_diamonds.png", "/Imagenes/5_of_diamonds.png", "/Imagenes/6_of_diamonds.png", "/Imagenes/7_of_diamonds.png", "/Imagenes/8_of_diamonds.png", "/Imagenes/9_of_diamonds.png", "/Imagenes/10_of_diamonds.png", "/Imagenes/jack_of_hearts2.png", "/Imagenes/queen_of_diamonds2.png", "/Imagenes/king_of_diamonds2.png"}
};
public Carta(int palo, int numero, int reverso)
{
this.palo = palo;
this.numero = numero;
this.reverso = reverso;
imagenCarta = new ImageIcon(getClass().getResource(todaCarta[palo][numero])); //Sabremos qué imagen le corresponde en función del palo y el numero
if(reverso == 1)
{
setIcon(imagenCarta);
}
else
{
setIcon(reversoCarta);
}
addMouseMotionListener(this);
Movimiento movimiento = new Movimiento(this);
addMouseListener(movimiento); //Le daremos el listener para poder arrastrarla por el panel
}
public int getReverso()
{
return reverso;
}
public void darLaVuelta()
{
/*if(getReverso() == 1)
{
setIcon(reversoCarta);
}
else
{
setIcon(imagenCarta);
}*/
setIcon(reversoCarta);
reverso = 0;
}
public void descubrir()
{
setIcon(imagenCarta);
reverso = 1;
}
public void setPosicion(int posicion)
{
posicionEnPila = posicion;
}
public int getPosicion()
{
return posicionEnPila;
}
public void setOrigin(int x, int y)
{
xOrigen = x;
yOrigen = y;
}
public int getOrigenX()
{
return xOrigen;
}
public int getOrigenY()
{
return yOrigen;
}
public int getPalo()
{
return this.palo;
}
public int getNumero()
{
return this.numero;
}
@Override
public void mouseDragged(MouseEvent e) //Aquí modificaremos su posicion en función de cuando la arrastremos
{
int posicionCarta;
int numeroDeCartas;
Carta[] aux = new Carta[13];
posicionCarta = this.getPosicion();
numeroDeCartas = this.getPilaOrigen(this.getOrigenX(), this.getOrigenY()).numeroCartas();
if(getReverso() == 1)
{
if(posicionCarta == numeroDeCartas - 1)
{
setLocation(this.getX() + e.getX() - this.getWidth() / 2, this.getY() + e.getY() - this.getHeight() / 2);
}
else if(this.getPilaOrigen(this.getOrigenX(), this.getOrigenY()) == todasLasCartas)
{
setLocation(this.getX() + e.getX() - this.getWidth() / 2, this.getY() + e.getY() - this.getHeight() / 2);
}
else
{
aux = this.getPilaOrigen(this.getOrigenX(), this.getOrigenY()).devolverBaraja();
setLocation(this.getX() + e.getX() - this.getWidth() / 2, this.getY() + e.getY() - this.getHeight() / 5);
int contador = 1;
for(int i = posicionCarta + 1; i < numeroDeCartas; i++)
{
aux[i].setLocation(this.getX() + e.getX() - this.getWidth() / 2, this.getY() + (30 * contador) + e.getY() - this.getHeight() / 5);
contador++;
}
}
}
}
@Override
public void mouseMoved(MouseEvent e) {
}
public Pila getPilaOrigen(int x, int y) //Con este metodo podremos saber en qué pila se encuentra la carta en función del origen de su x
{
if(x == 30)
{
return todasLasCartas;
}
else if(x == 157)
{
return primeraPila;
}
else if(x == 277)
{
return segundaPila;
}
else if(x == 407)
{
return terceraPila;
}
else if(x == 537)
{
return cuartaPila;
}
else if(x == 667)
{
return quintaPila;
}
else if(x == 797)
{
return sextaPila;
}
else if(x == 927)
{
return septimaPila;
}
else
{
if(y == 30)
{
return pilaDeOros;
}
else if(y == 229)
{
return pilaDeEspadas;
}
else if(y == 428)
{
return pilaDeBastos;
}
else
{
return pilaDeCopas;
}
}
}
class Movimiento implements MouseListener //Esta clase interna nos sirve para tener el método que nos diga cuándo hemos soltado la carta
{
Carta carta;
public Movimiento(Carta carta)
{
this.carta = carta;
}
@Override
public void mouseClicked(MouseEvent e){
//System.out.println("La carta esta en la posicion: " + getPosicion());
System.out.println("La pila de la carta es: " + getPilaOrigen(xOrigen, yOrigen));
}
;@Override public void mousePressed(MouseEvent e){};@Override public void mouseEntered(MouseEvent e){};@Override public void mouseExited(MouseEvent e){};
public void comProbarTerminar()
{
if(contadorPica == 12 && contadorTrevol == 12 && contadorCorazon == 12 && contadorDiamante == 12)
{
System.out.println("HAASSS GANADO");
System.exit(0);
}
}
@Override
public void mouseReleased(MouseEvent e)
{
int posicionPrevia = carta.getPosicion();
int numeroDeCartasPrevio = carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas();
Pila pilaPrevia = carta.getPilaOrigen(xOrigen, yOrigen);
Carta[] cartasEnPila = new Carta[52];
boolean ultimaCarta = true;
if(posicionPrevia != numeroDeCartasPrevio - 1)
{
cartasEnPila = carta.getPilaOrigen(xOrigen, yOrigen).devolverBaraja();
ultimaCarta = false;
for(int i = 0; i < numeroDeCartasPrevio; i++)
{
System.out.println(pilaPrevia.getCarta(i).getPalo());
}
}
if(getX() >= 140 && getX() < 260) //Si cuando la sueltas está en estas cordenadas, significa que será la primera pila
{
if(primeraPila.AñadirCarta(carta))
{
if(carta.getPilaOrigen(xOrigen, yOrigen) == todasLasCartas) //Si la carta viene de la pila de la baraja, habrá que darle un trato distinto a la hora de eliminarla(En especial si es la segunda vez que generamos las cartas
{
if(repeticion == 0)
{
setLocation(157, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta(); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(157, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
else
{
setLocation(157, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(157, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(157, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(157, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
if(ultimaCarta == false)
{
for(int i = 0; i < numeroDeCartasPrevio - 1; i++)
{
System.out.println(pilaPrevia.getCarta(i).getPalo());
}
for(int i = posicionPrevia; i < numeroDeCartasPrevio - 1; i++)
{
Carta cartaAux = pilaPrevia.getCarta(posicionPrevia);
primeraPila.AñadirCarta(pilaPrevia.getCarta(posicionPrevia));
pilaPrevia.QuitarCartaBaraja(posicionPrevia);
cartaAux.setLocation(157, 30 * (cartaAux.getPosicion() + 1));
cartaAux.setOrigin(157, 30 * (cartaAux.getPosicion() + 1));
}
}
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
//Cambiaremos su origen a esas coordenadas para que quede anclada ahí
// System.out.println("En la primera pila quedan " + carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas());
}
else
{
setLocation(xOrigen, yOrigen); //Si no se puede poner en estas coordenadas, vuelve al lugar donde estuviese anclada
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else if(getX() >= 260 && getX() < 390) //Mas de lo mismo, pero esta vez la segunda columna
{
if(segundaPila.AñadirCarta(carta))
{
if(carta.getPilaOrigen(xOrigen, yOrigen) == todasLasCartas)
{
if(repeticion == 0)
{
setLocation(277, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta(); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(277, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
else
{
setLocation(277, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(277, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(277, 30 * (getPosicion() + 1));
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia);
carta.setOrigin(277, 30 * (getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
if(ultimaCarta == false)
{
for(int i = 0; i < numeroDeCartasPrevio - 1; i++)
{
System.out.println(pilaPrevia.getCarta(i).getPalo());
}
for(int i = posicionPrevia; i < numeroDeCartasPrevio - 1; i++)
{
Carta cartaAux = pilaPrevia.getCarta(posicionPrevia);
segundaPila.AñadirCarta(pilaPrevia.getCarta(posicionPrevia));
pilaPrevia.QuitarCartaBaraja(posicionPrevia);
cartaAux.setLocation(277, 30 * (cartaAux.getPosicion() + 1));
cartaAux.setOrigin(277, 30 * (cartaAux.getPosicion() + 1));
}
}
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else if(getX() >= 390 && getX() < 520) //Mas de lo mismo, pero esta vez la tercera columna
{
if(terceraPila.AñadirCarta(carta))
{
if(carta.getPilaOrigen(xOrigen, yOrigen) == todasLasCartas)
{
if(repeticion == 0)
{
setLocation(407, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta(); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(407, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
else
{
setLocation(407, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(407, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(407, 30 * (getPosicion() + 1));
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia);
carta.setOrigin(407, 30 * (getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
if(ultimaCarta == false)
{
for(int i = 0; i < numeroDeCartasPrevio - 1; i++)
{
System.out.println(pilaPrevia.getCarta(i).getPalo());
}
for(int i = posicionPrevia; i < numeroDeCartasPrevio - 1; i++)
{
Carta cartaAux = pilaPrevia.getCarta(posicionPrevia);
terceraPila.AñadirCarta(pilaPrevia.getCarta(posicionPrevia));
pilaPrevia.QuitarCartaBaraja(posicionPrevia);
cartaAux.setLocation(407, 30 * (cartaAux.getPosicion() + 1));
cartaAux.setOrigin(407, 30 * (cartaAux.getPosicion() + 1));
}
}
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
// System.out.println("La posicion de la carta era: " + carta.getPosicion());
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else if(getX() >= 520 && getX() < 650) //Mas de lo mismo, pero esta vez la segunda columna
{
if(cuartaPila.AñadirCarta(carta))
{
if(carta.getPilaOrigen(xOrigen, yOrigen) == todasLasCartas)
{
if(repeticion == 0)
{
setLocation(537, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta(); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(537, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
else
{
setLocation(537, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(537, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(537, 30 * (getPosicion() + 1));
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia);
carta.setOrigin(537, 30 * (getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
if(ultimaCarta == false)
{
for(int i = 0; i < numeroDeCartasPrevio - 1; i++)
{
System.out.println(pilaPrevia.getCarta(i).getPalo());
}
for(int i = posicionPrevia; i < numeroDeCartasPrevio - 1; i++)
{
Carta cartaAux = pilaPrevia.getCarta(posicionPrevia);
cuartaPila.AñadirCarta(pilaPrevia.getCarta(posicionPrevia));
pilaPrevia.QuitarCartaBaraja(posicionPrevia);
cartaAux.setLocation(537, 30 * (cartaAux.getPosicion() + 1));
cartaAux.setOrigin(537, 30 * (cartaAux.getPosicion() + 1));
}
}
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
// System.out.println("La posicion de la carta era: " + carta.getPosicion());
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else if(getX() >= 650 && getX() < 780) //Mas de lo mismo, pero esta vez la segunda columna
{
if(quintaPila.AñadirCarta(carta))
{
if(carta.getPilaOrigen(xOrigen, yOrigen) == todasLasCartas)
{
if(repeticion == 0)
{
setLocation(667, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta(); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(667, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
else
{
setLocation(667, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(667, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(667, 30 * (getPosicion() + 1));
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia);
carta.setOrigin(667, 30 * (getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
if(ultimaCarta == false)
{
for(int i = posicionPrevia; i < numeroDeCartasPrevio - 1; i++)
{
Carta cartaAux = pilaPrevia.getCarta(posicionPrevia);
quintaPila.AñadirCarta(pilaPrevia.getCarta(posicionPrevia));
pilaPrevia.QuitarCartaBaraja(posicionPrevia);
cartaAux.setLocation(667, 30 * (cartaAux.getPosicion() + 1));
cartaAux.setOrigin(667, 30 * (cartaAux.getPosicion() + 1));
}
}
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
// System.out.println("La posicion de la carta era: " + carta.getPosicion());
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else if(getX() >= 780 && getX() < 910) //Mas de lo mismo, pero esta vez la segunda columna
{
if(sextaPila.AñadirCarta(carta))
{
if(carta.getPilaOrigen(xOrigen, yOrigen) == todasLasCartas)
{
if(repeticion == 0)
{
setLocation(797, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta(); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(797, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
else
{
setLocation(797, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(797, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(797, 30 * (getPosicion() + 1));
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia);
carta.setOrigin(797, 30* (getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
if(ultimaCarta == false)
{
for(int i = 0; i < numeroDeCartasPrevio - 1; i++)
{
System.out.println(pilaPrevia.getCarta(i).getPalo());
}
for(int i = posicionPrevia; i < numeroDeCartasPrevio - 1; i++)
{
Carta cartaAux = pilaPrevia.getCarta(posicionPrevia);
sextaPila.AñadirCarta(pilaPrevia.getCarta(posicionPrevia));
pilaPrevia.QuitarCartaBaraja(posicionPrevia);
cartaAux.setLocation(797, 30 * (cartaAux.getPosicion() + 1));
cartaAux.setOrigin(797, 30 * (cartaAux.getPosicion() + 1));
}
}
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
// System.out.println("La posicion de la carta era: " + carta.getPosicion());
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else if(getX() >= 910 && getX() < 1040) //Mas de lo mismo, pero esta vez la segunda columna
{
if(septimaPila.AñadirCarta(carta))
{
if(carta.getPilaOrigen(xOrigen, yOrigen) == todasLasCartas)
{
if(repeticion == 0)
{
setLocation(927, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta(); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(927, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
else
{
setLocation(927, 30 * (getPosicion() + 1)); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(927, 30 *(getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(927, 30 * (getPosicion() + 1));
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia);
carta.setOrigin(927, 30 * (getPosicion() + 1));
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
if(ultimaCarta == false)
{
for(int i = 0; i < numeroDeCartasPrevio - 1; i++)
{
System.out.println(pilaPrevia.getCarta(i).getPalo());
}
for(int i = posicionPrevia; i < numeroDeCartasPrevio - 1; i++)
{
Carta cartaAux = pilaPrevia.getCarta(posicionPrevia);
septimaPila.AñadirCarta(pilaPrevia.getCarta(posicionPrevia));
pilaPrevia.QuitarCartaBaraja(posicionPrevia);
cartaAux.setLocation(927, 30 * (cartaAux.getPosicion() + 1));
cartaAux.setOrigin(927, 30 * (cartaAux.getPosicion() + 1));
}
}
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
//System.out.println("La posicion de la carta era: " + carta.getPosicion());
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else if(getX() >= 1040 && getX() < 1170)
{
if(getY() >= 0 && getY() < 199)
{
if(pilaDeOros.CompletarPalo(carta))
{
if(carta.getPilaOrigen(xOrigen, yOrigen) == todasLasCartas)
{
if(repeticion == 0)
{
setLocation(1057, 30); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta(); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(1057, 30);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
else
{
setLocation(1057, 30); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(1057, 30);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(1057, 30);
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta();
carta.setOrigin(1057, 30);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
contadorPica++;
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else if(getY() >= 199 && getY() < 398)
{
if(pilaDeEspadas.CompletarPalo(carta))
{
if(carta.getPilaOrigen(xOrigen, yOrigen) == todasLasCartas)
{
if(repeticion == 0)
{
setLocation(1057, 229); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta(); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(1057, 229);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
else
{
setLocation(1057, 229); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(1057, 229);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(1057, 229);
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta();
carta.setOrigin(1057, 229);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
contadorTrevol++;
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else if(getY() >= 398 && getY() < 597)
{
if(pilaDeBastos.CompletarPalo(carta))
{
if(carta.getPilaOrigen(xOrigen, yOrigen) == todasLasCartas)
{
if(repeticion == 0)
{
setLocation(1057, 428); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta(); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(1057, 428);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
else
{
setLocation(1057, 428); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(1057, 428);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(1057, 428);
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta();
carta.setOrigin(1057, 428);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
contadorCorazon++;
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else if(getY() >= 597 && getY() < 796)
{
if(pilaDeCopas.CompletarPalo(carta))
{
if(carta.getPilaOrigen(xOrigen, yOrigen) == todasLasCartas)
{
if(repeticion == 0)
{
setLocation(1057, 627); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta(); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(1057, 627);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
else
{
setLocation(1057, 627); //Si se puede, pondremos la carta en el lugar de la pila que le corresponde
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCartaBaraja(posicionPrevia); //Quitaremos la carta de la pila en la que estuviera
carta.setOrigin(1057, 627);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
}
else
{
setLocation(1057, 627);
carta.getPilaOrigen(xOrigen, yOrigen).QuitarCarta();
carta.setOrigin(1057, 627);
if(decidirFichero % 2 == 0)
{
saveData("Deshacer.txt");
}
else
{
saveData("Deshacer2.txt");
}
decidirFichero++;
}
contadorDiamante++;
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
else
{
setLocation(xOrigen, yOrigen);
if(ultimaCarta == false)
{
for(int i = posicionPrevia + 1; i < carta.getPilaOrigen(xOrigen, yOrigen).numeroCartas(); i++)
{
cartasEnPila[i].setLocation(cartasEnPila[i].getOrigenX(), cartasEnPila[i].getOrigenY());
}
}
}
}
}
}
public class Pila
{
Carta[] columnaDeCartas = new Carta[52]; //Carta1 //Cada pila tendrá una cantidad de cartas posibles
int contadorDeCartas = 0; //Este es el contador que definirá en qué posicion va cada carta en la pila
int palo;
public Pila(int numero)
{
palo = numero;
}
public Carta[] devolverBaraja()
{
return columnaDeCartas;
}
public void cartaSiPrincipal(Carta carta)
{
columnaDeCartas[contadorDeCartas] = carta;
carta.setPosicion(contadorDeCartas);
contadorDeCartas++;
}
public int numeroCartas()
{
return contadorDeCartas;
}
public int getPaloPosicion(int posicion)
{
return columnaDeCartas[posicion].getPalo();
}
public int getNumeroPosicion(int posicion)
{
return columnaDeCartas[posicion].getNumero();
}
public Carta getCarta(int posicion)
{
return columnaDeCartas[posicion];
}
public void vaciarPila()
{
for(int i = 0; i < 52; i++)
{
columnaDeCartas[i] = null;
}
contadorDeCartas = 0;
}
public boolean AñadirCarta(Carta carta)
{
boolean colocada = false;
if(confirmarPosicion(carta)) //Si se puede colocar la carta
{
colocada = true;
columnaDeCartas[contadorDeCartas] = carta;
carta.setPosicion(contadorDeCartas); //Le indicamos a la propia carta su posicion en la pila
//Aumentamos el contador para indicar la siguiente posicion disponible
contadorDeCartas++;
}
return colocada;
}
public void QuitarCarta() //Para cuando movamos una carta de pila a otra y tengamos que eliminar la carta de nuestro array en la pila
{
//System.out.println("Quitando la carta en la posicion: " + contadorDeCartas);
columnaDeCartas[contadorDeCartas - 1] = null;
contadorDeCartas --; //Decrementamos el contador indicando la nueva posicion disponible
if(contadorDeCartas > 0)
{
columnaDeCartas[contadorDeCartas - 1].descubrir();
}
}
public void QuitarCartaBaraja(int posicion)
{
columnaDeCartas[posicion] = null;
if(contadorDeCartas - 1 == posicion)
{
columnaDeCartas[contadorDeCartas- 1] = null;
contadorDeCartas--;
}
else
{
for(int i = posicion; i < 51; i++)
{
columnaDeCartas[i] = columnaDeCartas[i + 1];
columnaDeCartas[i + 1] = null;
}
limite--;
contadorDeCartas--;
}
for(int i = 0; i < contadorDeCartas; i++)
{
columnaDeCartas[i].setPosicion(i);
}
if(contadorDeCartas > 0)
{
columnaDeCartas[contadorDeCartas - 1].descubrir();
}
}
public boolean confirmarPosicion(Carta carta /*Carta2*/)
{
boolean sePuede = false;
int contador = -1;
for(int i = 0; i < 52; i++)
{
if(columnaDeCartas[i] != null) //Recorremos la pila en busca de la última posicion disponible.
{
contador++;
}
}
//System.out.println("Se han encontrado " + contador + "CARTas");
if(contador == -1) //Si no hay ninguna carta en la pila, solo se podrá colocar un rey
{
if(carta.getNumero() == 12)
{
sePuede = true;
}
}
else
{
sePuede = MovimientoPosible(columnaDeCartas[contador], carta);
}
return sePuede;
}
public boolean MovimientoPosible(Carta carta1, Carta carta2) //La carta solo se podrá poner si el palo y el numero son adecuados.
{
if(carta1.getPalo() == 0 || carta1.getPalo() == 1)
{
if(carta2.getPalo() == 0 || carta2.getPalo() == 1)
{
return false;
}
if(carta1.getNumero() != carta2.getNumero() + 1)
{
return false;
}
}
else if(carta1.getPalo() == 2 || carta1.getPalo() == 3)
{
if(carta2.getPalo() == 2 || carta2.getPalo() == 3)
{
return false;
}
if(carta1.getNumero() != carta2.getNumero() + 1)
{
return false;
}
}
return true;
}
public boolean CompletarPalo(Carta carta)
{
boolean sePuede = true;
if(carta.getPalo() != palo)
{
return false;
}
if(contadorDeCartas == 0)
{
if(carta.getNumero() != 0)
{
return false;
}
}
else
{
if(carta.getNumero() - 1 != columnaDeCartas[contadorDeCartas - 1].getNumero())
{
return false;
}
}
columnaDeCartas[contadorDeCartas] = carta;
contadorDeCartas ++;
return sePuede;
}
}
}
|
abcca607d942bd07bd42f24ec9972d5103436b6e
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
aabadp02/SolitarioSwing
|
9633ae5c1a36437d2b8841937d2fe8301171a103
|
306e5306418281b8e0238019e9972e5360cd4f9b
|
refs/heads/master
|
<repo_name>ganzux/DynDNSUpdater<file_sep>/src/resources/config.properties
url.apis = http://api.externalip.net/ip/,http://myip.dnsomatic.com/,http://icanhazip.com
<file_sep>/README.md
DynDNSUpdater
=============
DynDNSUpdater
<file_sep>/src/com/ganzux/util/dyndns/gui/MainGui.java
package com.ganzux.util.dyndns.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class MainGui extends JFrame{
private JLabel lblNewLabel;
private JTextField user;
private JLabel lblNewLabel_1;
private JTextField path;
private JTextField pass;
JScrollPane scroll;
private JTextField minutes;
private JButton startButton = new JButton("Start !");
private JButton stopButton = new JButton("Stop");
private JTextArea out = new JTextArea();
private StringBuilder sb = new StringBuilder();
private Thread thread = null;
private DynThread runnable = null;
protected MainGui()
{
setTitle("DynDNS Updater");
setSize(400, 350);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JLabel lblDyndnsUpdater = new JLabel("DynDNS Updater");
lblDyndnsUpdater.setFont(new Font("Tahoma", Font.BOLD, 16));
lblDyndnsUpdater.setHorizontalAlignment(SwingConstants.CENTER);
lblDyndnsUpdater.setToolTipText("DynDNS Updater");
getContentPane().add(lblDyndnsUpdater, BorderLayout.NORTH);
out.setEditable(false);
out.setBackground(Color.BLACK);
out.setForeground(Color.GREEN);
out.setRows(8);
getContentPane().add(out, BorderLayout.SOUTH);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(0,2));
lblNewLabel = new JLabel("Path");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(lblNewLabel);
path = new JTextField();
path.setText("rpito.dyndns.org");
panel.add(path);
JLabel lblNewLabel_2 = new JLabel("User");
lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(lblNewLabel_2);
user = new JTextField();
user.setText("aamsc");
panel.add(user);
JLabel lblNewLabel_3 = new JLabel("Password");
lblNewLabel_3.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(lblNewLabel_3);
pass = new JPasswordField();
panel.add(pass);
pass.setText("");
pass.setColumns(10);
JLabel lblNewLabel_4 = new JLabel("Minutes");
lblNewLabel_4.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(lblNewLabel_4);
minutes = new JTextField();
panel.add(minutes);
minutes.setColumns(10);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
startAction();
}
});
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
stopAction();
}
});
getContentPane().add(startButton, BorderLayout.EAST);
scroll = new JScrollPane (out, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
getContentPane().add( scroll, BorderLayout.SOUTH);
prepareComponents(); // Throws the assertion error
setVisible(true); // This will paint the entire frame
}
/**
* Prepares the components for display.
*
* @throws AssertionError if not called on the EDT
*/
private void prepareComponents()
{
assert SwingUtilities.isEventDispatchThread();
}
/**
* @param args not used
*/
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
MainGui example = new MainGui();
}
});
}
private void startAction(){
OutUtil.getInstance().addText("Starting...", out);
if ( path.getText() != null && !path.getText().isEmpty() &&
pass.getText() != null && !pass.getText().isEmpty() &&
user.getText() != null && !user.getText().isEmpty() &&
minutes.getText() != null && !minutes.getText().isEmpty()
){
try{
int minutesInt = Integer.parseInt( minutes.getText() );
getContentPane().remove( startButton );
getContentPane().add(stopButton, BorderLayout.EAST);
path.setEditable( false );
pass.setEditable( false );
user.setEditable( false );
minutes.setEditable( false );
runnable = new DynThread( minutesInt, out, scroll, user.getText(),pass.getText(),path.getText() );
thread = new Thread(runnable);
thread.start();
OutUtil.getInstance().addText("Started", out);
} catch ( Exception e){
OutUtil.getInstance().addText("Minutes must be a number", out);
}
} else {
OutUtil.getInstance().addText("You must set all the paremeters", out);
}
}
private void stopAction(){
OutUtil.getInstance().addText("Stopping...", out);
OutUtil.getInstance().addText("Stopped", out);
getContentPane().remove( stopButton );
getContentPane().add(startButton, BorderLayout.EAST);
path.setEditable( true );
pass.setEditable( true );
user.setEditable( true );
minutes.setEditable( true );
if (thread != null) {
runnable.terminate();
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
<file_sep>/src/com/ganzux/util/dyndns/updater/DynDNSUpdater.java
package com.ganzux.util.dyndns.updater;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.xml.bind.DatatypeConverter;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
public class DynDNSUpdater {
///////////////////////////////////////////////////////////////
// SingleTon //
///////////////////////////////////////////////////////////////
private DynDNSUpdater(){
// logger.info("New instance for DynDNSUpdater");
prop = new Properties();
uris = new ArrayList<String>();
InputStream input = null;
try {
// logger.info("Trying to read properties...");
input = this.getClass().getClassLoader().getResourceAsStream("resources/config.properties");
prop.load( input );
// logger.info("properties readed");
String urls = prop.getProperty("url.apis");
if ( urls != null ){
// logger.info("Reading URL");
for ( String u:urls.split(",") ){
uris.add( u );
// logger.info( u );
}
}
} catch (IOException ex) {
// logger.error( ex.getMessage() );
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static DynDNSUpdater instance;
public static synchronized DynDNSUpdater getInstance(){
if ( instance == null )
instance = new DynDNSUpdater();
return instance;
}
///////////////////////////////////////////////////////////////
// End of SingleTon //
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
// Atributes //
///////////////////////////////////////////////////////////////
private Properties prop;
private List<String> uris;
// private static Logger logger = LoggerFactory.getLogger( DynDNSUpdater.class );
///////////////////////////////////////////////////////////////
// End Of Atributes //
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
// Public Methods //
///////////////////////////////////////////////////////////////
public String[] resetDynDNS( String nowPublicIP, String user, String pass, String path ){
String[] reset = new String[3];
try{
reset[0] = nowPublicIP;
String userpassword = user + ":" + pass;
String encodedAuthorization = DatatypeConverter.printBase64Binary(userpassword.getBytes());
// Connect to DynDNS
URL url = new URL("http://members.dyndns.org/nic/update?hostname=" + path + "&myip=" + nowPublicIP);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Demo DynDNS Updater");
connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
// Execute GET
int responseCode = connection.getResponseCode();
reset[1] = String.valueOf( responseCode );
// Print feedback
String line;
reset[2] = "";
InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());
BufferedReader buff = new BufferedReader(in);
do {
line = buff.readLine();
reset[2] += line;
} while (line != null);
connection.disconnect();
} catch (Exception ex) {
}
return reset;
}
public String[] resetDynDNS( String user, String pass, String path ){
return resetDynDNS( getPublicIP(), user, pass, path);
}
public String getPublicIP(){
try{
for ( String apiUrl:uris ){
URL myIP;
try{
myIP = new URL( apiUrl );
BufferedReader in = new BufferedReader( new InputStreamReader(myIP.openStream()) );
return in.readLine();
} catch ( Exception e ){
}
}
} catch ( Exception e ){
}
return null;
}
///////////////////////////////////////////////////////////////
// End of Public Methods //
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
// Private Methods //
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
// End of Private Methods //
///////////////////////////////////////////////////////////////
}
|
71afe2cdb8dc2907eed8d6560e320d427e5ee019
|
[
"Markdown",
"Java",
"INI"
] | 4
|
INI
|
ganzux/DynDNSUpdater
|
09f37f1b83668638e791187d38ae377a4eca077f
|
328f3586ae599ca1109f4a5c58c89a4ee86a3a46
|
refs/heads/master
|
<file_sep>import styled from 'styled-components';
const StyledMainTitle = styled.h1`
font-family: 'Roboto Mono', monospace;
font-size:x-large;
`;
const StyledSecondTitle = styled.h2`
font-family: 'Open Sans', sans-serif;
font-size:medium;
`;
const StyledText = styled.p`
font-family: 'Open Sans', sans-serif;
font-size:small;
`
const InstaCaption = styled.p`
padding:0px 20px;
font-family: 'Open Sans', sans-serif;
font-size:small;
color:#4D4D4F;
`
export {
StyledMainTitle,
StyledSecondTitle,
StyledText,
InstaCaption
}
<file_sep>import React from 'react';
import {StyledMainTitle, StyledSecondTitle} from 'components/StyledTexts';
import Zombie from 'media/zombie.svg'
const GoBackToWork = ()=>{
return(
<>
<StyledMainTitle>How many posts do you need!?!</StyledMainTitle>
<StyledSecondTitle>You social zombie... Seriously I'm sure you can find better things to do!</StyledSecondTitle>
<img src={Zombie} style={{width:100}} alt="zombie"/>
</>
)
}
export default GoBackToWork
<file_sep>import React, {Component} from 'react';
import {connect} from 'react-redux';
import * as actions from 'actions';
import {getRndInteger} from 'helpers';
import {FaCamera, FaQuestionCircle} from 'react-icons/fa';
import {MdChatBubble} from 'react-icons/md';
import {StyledButton, StyledButtonWrapper} from 'components/StyledButton';
import {StyledMainTitle, StyledSecondTitle, StyledText} from 'components/StyledTexts';
import {SettingsWrapper} from 'components/StyledWrappers';
import styled from 'styled-components';
const StyledTextArea = styled.textarea`
background-color:white;
min-height:100px;
width:100%;
border-radius: 5px;
border-color: lightgray;
margin:10px;
`;
class SettingsBox extends Component {
state={
comment:''
};
handleChange =(event)=>{
this.setState({comment:event.target.value});
}
handleSubmit = (event) =>{
event.preventDefault();
this.props.saveText(this.state.comment);
this.setState({comment:''});
};
handleImageFetch = ()=>{
if(this.props.imagesList && this.props.imageId+1<this.props.imagesList.length-1){
this.props.changeImage();
}
else{
let pageIndex = -1;
if(!this.props.imagePageIndex){
pageIndex = getRndInteger(0,34)
}
else if(this.props.imagePageIndex && this.props.imagePageIndex+1<35){
pageIndex = this.props.imagePageIndex
}
this.props.fetchImages(pageIndex)
}
}
render(){
return(
<SettingsWrapper>
<StyledMainTitle>Get Me A Post!</StyledMainTitle>
<StyledText>a simple post generator for overworked influencers </StyledText>
<StyledButtonWrapper>
<StyledButton onClick={this.handleImageFetch} className='fetch-image'>
Get me an Image <FaCamera/>
</StyledButton>
</StyledButtonWrapper>
<form onSubmit={this.handleSubmit}>
<StyledTextArea
placeholder="Type your comment here..."
onChange={this.handleChange}
value={this.state.comment}
maxLength='2200'
/>
<StyledButtonWrapper>
<StyledButton>Submit my comment <MdChatBubble/></StyledButton>
</StyledButtonWrapper>
</form>
<StyledSecondTitle>No inspiration? No worries! </StyledSecondTitle>
<StyledButtonWrapper>
<StyledButton className="fetch-comments" onClick={this.props.fetchText}>
Fetch me a comment <FaQuestionCircle/>
</StyledButton>
</StyledButtonWrapper>
</SettingsWrapper>
)
}
}
function mapStateToProps(state){
return {...state.post};
}
export default connect(mapStateToProps, actions)(SettingsBox);
<file_sep>import styled from 'styled-components';
const PostFactoryWrapper = styled.div`
padding:20px;
display: flex;
align-items: center;
justify-content: space-between;
min-height: 85vh;
max-width: 800px;
margin: 0 auto;
@media (max-width: 810px) {
flex-direction: column;
}
`
const WarningWrapper = styled(PostFactoryWrapper)`
flex-direction:column;
justify-content:center;
`;
const SettingsWrapper = styled.div`
text-align:center;
padding: 40px;
border-radius: 5px;
border: 2px solid #EE5160;
@media (max-width: 810px) {
padding: 20px;
}
`;
const PreviewWrapper = styled.div`
max-width:350px;
box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
border-radius:3px;
padding:20px;
@media (max-width: 810px) {
margin-top: 30px;
}
`
const CollectionWrapper = styled.div`
text-align:center;
`;
const PreviewBgImg = styled.div`
background:url(${props => props.image});
background-size : 100% auto;
background-repeat : no-repeat;
background-position-y : 20px;
`;
const PostItemsImageBg = styled(PreviewBgImg)`
min-height:150px;
background-size:cover;
background-position:center;
`;
export {
PostFactoryWrapper,
SettingsWrapper,
PreviewWrapper,
CollectionWrapper,
WarningWrapper,
PreviewBgImg,
PostItemsImageBg
}
<file_sep>import React, {Component} from 'react';
import {connect} from 'react-redux';
import * as actions from 'actions';
import {StyledSecondTitle} from 'components/StyledTexts';
import {CollectionWrapper} from 'components/StyledWrappers';
import PostItem from 'components/PostItem';
import styled from 'styled-components';
const PostsList = styled.div`
display: flex;
flex-wrap:wrap;
text-align: center;
max-width: 1000px;
margin: 0 auto;
`;
class PostCollection extends Component {
renderSavedPosts=()=>{
return this.props.savedPosts.map((data, key) => {
return (
<PostItem
image={data.imageUrl}
text={data.imageText}
key={key}
postId={key}
/>
)
})
}
pickTitle = ()=>{
const postsNumber = this.props.savedPosts.length
if(postsNumber>4 && postsNumber<=8){
return 'Impressive Collection!';
}
else if(postsNumber>8 && postsNumber<=12){
return 'You\'ve been knighted Insta Master!';
}
else if(postsNumber>12){
return 'OMG get a life...';
}
else {
return 'Taking it one post at a time.';
}
}
render(){
return(
<CollectionWrapper>
<StyledSecondTitle>{this.pickTitle()}</StyledSecondTitle>
<PostsList>
{this.renderSavedPosts()}
</PostsList>
</CollectionWrapper>
)
}
};
function mapStateToProps(state){
return {...state.post};
}
export default connect(mapStateToProps, actions)(PostCollection);
<file_sep>import React from 'react';
import {mount} from 'enzyme';
import SettingsBox from 'components/SettingsBox';
import Root from 'Root';
let wrapped
beforeEach(()=>{
wrapped = mount(
<Root>
<SettingsBox/>
</Root>
);
});
afterEach(()=>{
wrapped.unmount();
});
it('has a text area and 3 button', ()=>{
expect(wrapped.find('button').length).toEqual(3);
expect(wrapped.find('textarea').length).toEqual(1);
})
describe('the text area', ()=>{
beforeEach(()=>{
wrapped.find('textarea').simulate('change', {
target:{value:'new comment'}
});
wrapped.update();
})
it('has a text area that users can type in', ()=>{
expect(wrapped.find('textarea').prop('value')).toEqual('new comment')
});
it('clicking submit empties value', ()=>{
wrapped.find('form').simulate('submit');
wrapped.update();
expect(wrapped.find('textarea').prop('value')).toEqual('')
});
})
<file_sep>import React from 'react';
import {mount} from 'enzyme';
import App from 'components/App';
import Root from 'root';
import SettingsBox from 'components/SettingsBox';
import PostPreview from 'components/PostPreview';
import PostCollection from 'components/PostCollection';
import GoBackToWork from 'components/GoBackToWork';
let wrapped;
const basePost = {imageUrl:'imageurl',imageText:'myText'};
afterEach(()=>{
wrapped.unmount();
});
describe('0 posts in memory', ()=>{
beforeEach(()=>{
const initialState = {post : {savedPosts:[]}};
wrapped = mount(
<Root initialState={initialState}>
<App/>
</Root>
);
});
it('shows setting box and post preview', ()=>{
expect(wrapped.find(SettingsBox).length).toEqual(1);
expect(wrapped.find(PostPreview).length).toEqual(1);
});
});
describe('2 posts in memory', ()=>{
beforeEach(()=>{
const initialState = {post : {savedPosts:Array(2).fill(basePost)}};
wrapped = mount(
<Root initialState={initialState}>
<App/>
</Root>
);
});
it('shows setting box and post preview', ()=>{
expect(wrapped.find(SettingsBox).length).toEqual(1);
expect(wrapped.find(PostPreview).length).toEqual(1);
});
it('shows a post collection', ()=>{
expect(wrapped.find(PostCollection).length).toEqual(1);
})
});
describe('30 posts in memory', ()=>{
beforeEach(()=>{
const initialState = {post : {savedPosts:Array(30).fill(basePost)}};
wrapped = mount(
<Root initialState={initialState}>
<App/>
</Root>
);
});
it('shows go back to work message', ()=>{
expect(wrapped.find(GoBackToWork).length).toEqual(1);
});
it('shows a post collection', ()=>{
expect(wrapped.find(PostCollection).length).toEqual(1);
})
});
<file_sep>import React from 'react';
import {mount} from 'enzyme';
import moxios from 'moxios';
import Root from 'root';
import App from 'components/App';
import {PreviewBgImg} from 'components/StyledWrappers';
import PostItem from 'components/PostItem';
afterEach(()=>{
moxios.uninstall();
});
describe('Comment Fetch', ()=>{
beforeEach(()=>{
moxios.install();
moxios.stubRequest('https://uselessfacts.jsph.pl/random.json?language=en', {
status: 200,
response: {text:'test fetched text'}
});
});
it('can fetch a comment and display it in preview', (done)=>{
const wrapped = mount(
<Root>
<App/>
</Root>
)
wrapped.find('button.fetch-comments').simulate('click');
moxios.wait(()=>{
wrapped.update();
expect(wrapped.render().text()).toContain('test fetched text')
done(); //set test as finished
wrapped.unmount();
}, 200);
});
});
describe('Image Fetch', ()=>{
beforeEach(()=>{
moxios.install();
moxios.stubRequest('https://picsum.photos/v2/list?page=10', {
status: 200,
response: [{download_url:'https://page10/image1/600/600'}]
});
});
it('fetches new image list and display first in preview when reaching end of imageList', (done)=>{
const initialState={
post:{
imagePageIndex:9,
imagesList:[
{download_url:'https://page9/image1/600/600'},
{download_url:'https://page9/image2/600/600'}
],
imagesId:1
}
}
const wrapped = mount(
<Root initialState={initialState}>
<App/>
</Root>
)
wrapped.find(PreviewBgImg).prop("image")
wrapped.find('button.fetch-image').simulate('click');
moxios.wait(()=>{
wrapped.update();
expect(wrapped.find(PreviewBgImg).prop("image")).toEqual('https://page10/image1/400/400');
done(); //set test as finished
wrapped.unmount();
}, 200);
});
});
describe('Change image', ()=>{
const initialState = {
post : {
imagesList:[
{download_url:'https://page9/image1/600/600'},
{download_url:'https://page9/image2/600/600'},
{download_url:'https://page9/image3/600/600'},
{download_url:'https://page9/image4/600/600'}
],
imageId:1,
imageUrl:'https://page9/image2/400/400'
}
};
const wrapped = mount(
<Root initialState={initialState}>
<App/>
</Root>
);
it('changes image when clicking fetch image button', ()=>{
expect(wrapped.find(PreviewBgImg).prop("image")).toEqual('https://page9/image2/400/400')
wrapped.find('button.fetch-image').simulate('click');
wrapped.update();
expect(wrapped.find(PreviewBgImg).prop("image")).toEqual('https://page9/image3/400/400');
});
});
describe('Post deletion', ()=>{
const initialState = {
post : {
savedPosts:[
{
imageUrl:'https://page9/image1/600/600',
imageText:"Text1"
},
{
imageUrl:'https://page9/image2/600/600',
imageText:'Text2'
},
{
imageUrl:'https://page9/image3/600/600',
imageText:'Text3'
}
],
}
};
const wrapped = mount(
<Root initialState={initialState}>
<App/>
</Root>
);
it('deleting post when clicking deleting post button', ()=>{
wrapped.find('.delete-btn').first().simulate('click');
wrapped.update();
expect(wrapped.find(PostItem).length).toEqual(2);
expect(wrapped.render().text()).toContain('Text2');
expect(wrapped.render().text()).toContain('Text3');
});
});
<file_sep>import axios from 'axios';
import {
SAVE_TEXT,
FETCH_TEXT,
FETCH_IMAGE,
CHANGE_IMAGE,
SAVE_POST,
DELETE_POST
} from 'actions/types';
let response;
export function saveText(text){
return {
type: SAVE_TEXT,
payload: text
};
}
export function fetchText(){
response = axios.get('https://uselessfacts.jsph.pl/random.json?language=en')
return{
type : FETCH_TEXT,
payload : response
}
}
export function fetchImages(imagePageIndex){
response = axios.get(`https://picsum.photos/v2/list?page=${imagePageIndex+1}`)
return {
type : FETCH_IMAGE,
payload : response,
meta:{
imagePageIndex : imagePageIndex+1
}
}
}
export function changeImage(){
return {
type : CHANGE_IMAGE
}
}
export function savePost(){
return {
type : SAVE_POST
}
}
export function deletePost(postId){
return{
type:DELETE_POST,
payload:postId
}
}
<file_sep>import React from 'react';
import SettingsBox from 'components/SettingsBox';
import PostPreview from 'components/PostPreview';
import PostCollection from 'components/PostCollection';
import {PostFactoryWrapper, WarningWrapper} from 'components/StyledWrappers';
import GoBackToWork from 'components/GoBackToWork';
import {connect} from 'react-redux';
const App = (props)=>{
return(
<>
{
(props.savedPosts && props.savedPosts.length>15)
?
<WarningWrapper>
<GoBackToWork/>
</WarningWrapper>
:
<PostFactoryWrapper>
<SettingsBox/>
<PostPreview/>
</PostFactoryWrapper>
}
{(props.savedPosts && props.savedPosts.length>0)&&
<PostCollection/>
}
</>
)
}
function mapStateToProps(state){
return {savedPosts:state.post.savedPosts};
}
export default connect(mapStateToProps,)(App);
<file_sep>import React from 'react';
import {connect} from 'react-redux';
import * as actions from 'actions';
import {InstaCaption, StyledText} from 'components/StyledTexts';
import styled from 'styled-components';
import {AiFillDelete} from 'react-icons/ai';
import {PostItemsImageBg} from 'components/StyledWrappers';
const PostWrapper = styled.div`
box-shadow : 0 1px #FFFFFF inset, 0 1px 3px rgba(34, 25, 25, 0.4);
border-radius: 2px;
height:100%;
`;
const PostSpacer = styled.div`
padding:1%;
width:23%;
@media (max-width: 810px) {
width: 31%;
}
@media (max-width: 530px) {
width: 47%;
}
@media (max-width: 400px) {
width: 98%;
}
`;
const TitleWrapper = styled.div`
display:flex;
align-items:center;
justify-content:space-between;
padding:0px 15px;
`;
const PostItem = (props)=>{
return(
<PostSpacer>
<PostWrapper>
<TitleWrapper>
<StyledText>Post #{parseInt(props.postId)+1}</StyledText>
<AiFillDelete
style={{cursor:'pointer'}}
onClick={()=>props.deletePost(props.postId)}
className="delete-btn"
/>
</TitleWrapper>
<PostItemsImageBg image={props.image}></PostItemsImageBg>
<InstaCaption>{props.text}</InstaCaption>
</PostWrapper>
</PostSpacer>
)
}
export default connect(null, actions)(PostItem);
<file_sep>## Get Me A Post App
Une application pour les influenceurs surmenés! :camera:
- Développé en React + Redux + Styled Components + Axios
- Tests avec Jest et Enzyme
- Créé sur la base de [Create React App](https://github.com/facebook/create-react-app)
Pour voir l'app en live : [GetMeAPostApp](https://lucieo.github.io/GetMeAPost/)
|
2cc3775294a8900341791aacd4519a464f4406fc
|
[
"JavaScript",
"Markdown"
] | 12
|
JavaScript
|
Lucieo/GetMeAPost
|
9e9233d078a3446dc37d4391eb802922fdab01a4
|
dccbc75187e96596c4f0c00e54ecb78ee862f52b
|
refs/heads/master
|
<file_sep>// Request module is used to make the multiple GET requests
const request = require('request');
// Bluebird is used to create promises for an asynchronous process
const bluebird = require('bluebird');
// Function which requests initial raw data dump
// Returns the title, budget and year data for each winner
const getWinnerList = () => (
new Promise((resolve, reject) => {
request.get({
method: 'GET',
url: 'http://oscars.yipitdata.com'
}, (err, results) => {
if (err) {
reject(err);
} else {
// winnerList array initialized
let winnerList = [];
// Grab raw data from the body of the JSON object
const rawData = JSON.parse(results.body).results;
// Iterate through every grouped list of films by year
rawData.forEach((nominatedFilms, index) => {
// Iterate through each film in that year's group
nominatedFilms.films.forEach((film) => {
// If the film was a winner
if (film['Winner'] == true) {
// Grab the title (and remove unnecessary brackets)
const title = film['Film'].replace(/ *\[[^)]*\] */g, "");
// Grab the year data (and remove unnecessary info)
const year = nominatedFilms['year'].slice(0, 4);
// Grab the detail Url which we'll later use to get the budget
const detailUrl = film['Detail URL'];
// Add the film details to the winnerList
winnerList.push({'title': title, 'year': year, 'detailUrl': detailUrl});
}
})
})
// Return with the winner list
resolve(winnerList);
}
})
})
)
// Get request to grab Detail URL data
const detailUrlRequest = (detailUrl) => (
new Promise((resolve, reject) => {
request.get({
method: 'GET',
url: detailUrl
}, (err, results) => {
if (err) {
reject(err);
} else {
// Return full object which includes the budget
resolve(results);
}
})
})
)
// Function for cleaning up inconsistent budget entries
const budgetScrubber = (item) => {
if (item !== undefined) {
// Remove the unncecessary brackets
item = item.replace(/ *\[[^)]*\] */g, "")
// Remove 'US' and 'USD' (only two cases currently)
item = item.replace(/US\$ |US\$|US|USD\$ \$/g,'$');
// Declare number variable which will be mutated
let number;
// Case One: budget is in written actual number form
if (item.search('million') === -1) {
// Currency type in all current cases is at position 0
const currency = item[0];
// Parse out just the number and leave in string form
number = item.slice(1, item.length).split(' ')[0]
// Convert to Number type
number = Number(number.replace(/,/g, ''));
// Edge case: if currency was in British Pounds
if (currency === '£') {
// Using a historical average estimate
// I would improve this accuracy by using another API to grab exchange rate for that year
number *= 1.7;
}
// Case Two: budget is in english form with 'million'
} else if (item.search('million') !== -1) {
// Currency type in all current cases is at position 0
const currency = item[0];
// Remove everything but the number estimate
// I'm also choosing the USD number if two are given (rationale: exchange rate fluctuations)
number = item.slice(1, item.length).replace(/million/g, '').split(' ')[0]
// Account for ranges by taking the midpoint
if (number.search('–') !== -1 || number.search('-') !== -1) {
// Range has been found so I'm calculating the midpoint
// Make the dash type consistent before splitting into two numbers (to avoid errors)
number = number.replace(/–|-/g, '-');
number = number.split('-');
// Replace number with average of the two numbers
number = (Number(number[0]) + Number(number[1])) / 2;
// Convert the midpoint to a million figure
number *= 1000000;
// For cases where a '-' range wasn't given
} else {
// Convert string to million
number = Number(number) * 1000000;
// Account for British Pound conversion
if (currency === '£') {
// Using a historical average estimate
// I would improve this accuracy by using another API to grab exchange rate for that year
number *= 1.7;
}
}
}
// Round all numbers to nearest integer before returning
number = Math.round(number);
return number;
}
}
// This function logs the year, title and budget for each winner and the average budget
const logWinners = (winnerList) => {
// Declare a cache object to tally the budget total and number of films
// This will later be used to show the average budget when our recursive helper function is finished
let budgetObj = {
aggregateSum: 0,
numberOfFilms: 0
}
// This helper function iterates asynchronously through each winner in the list
const recursiveHelper = (list) => {
// Recursive base case:
// Print the average budget when we have finished iterating through every winner in the list
if (list.length === 0) {
console.log(`Average budget: $${Math.round(budgetObj.aggregateSum / budgetObj.numberOfFilms).toLocaleString()}`)
}
// Use the detailUrlRequest promise function to get the budget data
detailUrlRequest(list[0].detailUrl).then((data) => {
// Parse JSON data returned by the GET request
let budget = JSON.parse(data.body).Budget;
// Scrub the budget data
budget = budgetScrubber(budget);
// If budget is not undefined
if (budget !== undefined) {
// Add budget to the winners' aggregated total
budgetObj.aggregateSum += budget;
// Increment the number of winners by 1
budgetObj.numberOfFilms++;
// Change the budget to be human readable in currency form
budget = `$${Math.round(budget).toLocaleString()}`;
} else {
// Change budget from undefined to N/A
budget = 'N/A'
}
// Log the year, title and budget
console.log(`Year: ${list[0].year}, Title: ${list[0].title}, Budget: ${budget}`);
// Recursive case: call the recursive helper to continue iterating through the list
recursiveHelper(list.slice(1));
})
}
// Kick off the recursive helper function
recursiveHelper(winnerList);
}
// Step 1: Request the list of winners, then execute the logWinners function
getWinnerList().then((list) => {
// Step 2: execute the function to log all winner data and end with the average budget
logWinners(list);
});
<file_sep>#Instructions to run script
In the terminal from the root folder please run `npm install` to install node_module dependencies
`npm start` to run the oscarData.js script
Note: each year's winning title and budget will be logged to your terminal
#Estimated average budget of all winners (1927 - 2014)
$17,260,453
#Brief summary of my approach
My approach follows three steps:
1. Gather the list of winners for every year (Title, Year and Detail URL) with a GET request to 'http://oscars.yipitdata.com/'
2. Iterate through the list of winners and make a GET request to the winner's "Detail URL" to obtain the budget
3. Scrub various edge cases of the budget (brackets, foreign currency conversions, etc.)
Steps 1 and 2 above are straightforward, but assumptions were required for scrubbing the budget data and making it consistent.
Below is a general outline of my approach to cleaning up edge cases in the budget data:
- Remove extraneous notations that come after the budget number (e.g., bracket notations, "est." flags, etc.)
- If two budget numbers are given (e.g., one USD and one GBP), use the USD number
- If a number is written in english (e.g., "$2 million"), convert it to a real number (e.g., "$2,000,000")
- If no budget is defined, mark as "N/A" and don't include in the average budget calculation
- If a budget lower and upper bound range is given, take the average of the range
- If a budget is given in British Pounds, I used a 1.7 currency conversion. This could be later improved by taking the actual exchange rate for that year.
|
d9df70fd8c09d0b2fa98adca4e97c8a659a76691
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
n-white/oscarData
|
3b6452ed1caf1c27d62d4250baffbabd25362660
|
72b9b4bf15e40f6db82c490f649e5220e735d8b8
|
refs/heads/master
|
<repo_name>Eurekainc/Travel-Mate<file_sep>/Android/app/src/main/java/io/github/project_travel_mate/travel/transport/TrainAdapter.java
package io.github.project_travel_mate.travel.transport;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.github.project_travel_mate.R;
class TrainAdapter extends BaseAdapter {
private final Context mContext;
private final JSONArray mFeedItems;
private final LayoutInflater mInflater;
TrainAdapter(Context context, JSONArray feedItems) {
this.mContext = context;
this.mFeedItems = feedItems;
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mFeedItems.length();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
try {
return mFeedItems.getJSONObject(position);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View vi = convertView;
if (vi == null) {
vi = mInflater.inflate(R.layout.train_listitem, parent, false);
holder = new ViewHolder(vi);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
try {
holder.title.setText(mFeedItems.getJSONObject(position).getString("name"));
String descriptionText = "Train Number : " +
mFeedItems.getJSONObject(position).getString("train_number");
String aTimeText = "Arrival Time : " + mFeedItems.getJSONObject(position).getString("arrival_time");
String dTimeText = "Departure Time : " + mFeedItems.getJSONObject(position).getString("departure_time");
holder.description.setText(descriptionText);
holder.atime.setText(aTimeText);
holder.dtime.setText(dTimeText);
JSONArray ar = mFeedItems.getJSONObject(position).getJSONArray("days");
for (int i = 0; i < ar.length(); i++) {
int m = ar.getInt(i);
if (m == 1)
continue;
switch (i) {
case 0:
holder.d0.setText("N");
holder.d0.setBackgroundResource(R.color.red);
break;
case 1:
holder.d1.setText("N");
holder.d1.setBackgroundResource(R.color.red);
break;
case 2:
holder.d2.setText("N");
holder.d2.setBackgroundResource(R.color.red);
break;
case 3:
holder.d3.setText("N");
holder.d3.setBackgroundResource(R.color.red);
break;
case 4:
holder.d4.setText("N");
holder.d4.setBackgroundResource(R.color.red);
break;
case 5:
holder.d5.setText("N");
holder.d5.setBackgroundResource(R.color.red);
break;
case 6:
holder.d6.setText("N");
holder.d6.setBackgroundResource(R.color.red);
break;
}
}
holder.more.setOnClickListener(view -> {
Intent browserIntent = null;
try {
browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.cleartrip.com/trains/" +
mFeedItems.getJSONObject(position).getString("train_number")));
} catch (JSONException e1) {
e1.printStackTrace();
}
mContext.startActivity(browserIntent);
});
holder.book.setOnClickListener(view -> {
try {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.cleartrip.com/trains/" +
mFeedItems.getJSONObject(position).getString("train_number")));
mContext.startActivity(intent);
} catch (JSONException e12) {
e12.printStackTrace();
}
});
} catch (JSONException e) {
e.printStackTrace();
Log.e("ERROR : ", "Message : " + e.getMessage());
}
return vi;
}
class ViewHolder {
@BindView(R.id.train_name)
TextView title;
@BindView(R.id.traintype)
TextView description;
@BindView(R.id.arr)
TextView atime;
@BindView(R.id.dep)
TextView dtime;
@BindView(R.id.more)
Button more;
@BindView(R.id.book)
Button book;
@BindView(R.id.d0)
TextView d0;
@BindView(R.id.d1)
TextView d1;
@BindView(R.id.d2)
TextView d2;
@BindView(R.id.d3)
TextView d3;
@BindView(R.id.d4)
TextView d4;
@BindView(R.id.d5)
TextView d5;
@BindView(R.id.d6)
TextView d6;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
|
02b8a89ea19ce80707d624086c2fe6d8d7b5821b
|
[
"Java"
] | 1
|
Java
|
Eurekainc/Travel-Mate
|
8be7ebb7d57a9b2c518e7676f4cfba08b4449dc1
|
23983a1801c274492c778ac2fca819892003f207
|
refs/heads/main
|
<repo_name>TwentyE/Schulwebsite_By_J_L<file_sep>/School_Website/online_courses.php
<?php include("meta.php") ?>
<?php include("header.php") ?>
<?php
if (isset($session_fullName)) {
?> <div id="Videos">
<center>
<h1>3 Gratis-Kurse:</h1>
<br>
<h2>Wo ist die Liebe?</h2>
<iframe width="560" height="315" src="https://www.youtube.com/embed/RSkrUUYTkBs" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<br><br><br><br>
<h2>Frohe Weihnachten-Special Teil 1</h2>
<iframe width="560" height="315" src="https://www.youtube.com/embed/PAHCg7AnQXI" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<br><br><br><br>
<h2>Greenscreen</h2>
<iframe width="560" height="315" src="https://www.youtube.com/embed/SNNZ-ZG_j4M" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<?php
} else {
echo 'Du musst dich Anmelden um auf diese Seite zu gelangen';
}
?>
<?php include("footer.php") ?>
<file_sep>/School_Website/account.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<?php include("meta.php") ?>
<body>
<?php include("header.php") ?>
<section2>
<?php
if(!isset($_SESSION['login_id'])){
header("location: form.php"); // Redirecting To login
}
echo '<div style="font-size: 35px;">
<strong>Profil</strong>
<br>'
. $session_fullName
. '<br>
<a href="logout.php">Ausloggen</a>
</div>';
?>
</section2>
<?php include("footer.php") ?>
</div>
</body>
</html>
<file_sep>/School_Website/videos.php
<?php include("meta.php") ?>
<?php include("header.php") ?>
<div id="Videos">
<center>
<h1>Einige unserer Videos:</h1>
<br>
<h2>Wo ist die Liebe?</h2>
<iframe width="560" height="315" src="https://www.youtube.com/embed/RSkrUUYTkBs" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<br><br><br><br>
<h2>Frohe Weihnachten-Special Teil 1</h2>
<iframe width="560" height="315" src="https://www.youtube.com/embed/PAHCg7AnQXI" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<br><br><br><br>
<h2>Frohe Weihnachten-Special Teil 1</h2>
<iframe width="560" height="315" src="https://www.youtube.com/embed/eqUuEBShko0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<br><br><br><br>
<h2>Die Zukunft in der Vergangenheit</h2>
<iframe width="560" height="315" src="https://www.youtube.com/embed/NR8PcuG5daE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<br><br><br><br>
<h2>Der Cringe</h2>
<iframe width="560" height="315" src="https://www.youtube.com/embed/pedyG9lGNA0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</center>
<?php include("footer.php") ?>
<file_sep>/README.md
# Schulwebsite_By_J_L
We're recreating our school website because our school's website sucks!
You can copy the code, but please Link us in the Discription.
<file_sep>/School_Website/search.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<?php include("meta.php") ?>
<body>
<?php include("header.php") ?>
<section>
<div id="Vertretungsplan">
<h1>Vertretungsplan</h1>
$xml=simplexml_load_file("plan.xml") or die("Error: Cannot create object");
echo $xml->Kurz . "<br>";
echo $xml->le . "<br>";
<a><h3>Gib hier deine Klasse ein:
<form method="get" action="../search.php" />
<input type="text" id="keyword" name="keyword" value="Gib hier deine Klasse ein" onfocus="if (this.value=='Gib hier deine Klasse ein') {this.value=''; this.style.color='#696969';}" onclick="clickclear(this, 'Search [var.site_name]')" onblur="clickrecall(this,'Search [var.site_name]')" />
</form>
</div></h3></a>
<br><br>
Unser Vertretungsplan ist in der Beta-Version. Bei Problemen oder Bugs melden Sie sich bei uns über unseren Discord Server (<a href="https://discord.gg/WwJTKtqC">Discord</a>)
</div>
</section>
<?php include("footer.php") ?>
</div>
</body>
</html>
<file_sep>/School_Website/contact.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<?php include("meta.php") ?>
<body>
<?php include("header.php") ?>
<section>
<div id="Kontakte">
<h1>Kontakt</h1>
<a>Name:</a>
<p><NAME></p>
<a>Telefon:</a>
<address>
<p><a href="tel:017685483709" style="color: #BDBDBD">0176 85483709</a></p>
</address>
<a>E-Mail:</a>
<p><a href="email.html" style="color: #BDBDBD"><EMAIL></a></p>
<a>Wohnort:</a>
<p>Leipzig/Gohlis/Makleeberg/Holzhausen</p>
<div style='height:150px;width:100%;'><iframe width="" height="150" src=https://maps.google.de/maps?hl=de&q=%20Richterstraße+21%20Leipzig&t=&z=10&ie=utf8&iwloc=b&output=embed frameborder="0" scrolling="no" marginheight="0" marginwidth="0" style='height:150px;width:100%;'></iframe><p style="text-align:right; margin:0px; padding-top:-10px; line-height:10px;font-size:10px;margin-top: -25px;"><a href="http://www.checkpoll.de/google-maps-generator/" style="font-size:10px;" target="_blank">Google Maps Generator</a> by <a href="https://www.on-projects.de/" style="font-size:10px;" title="" target="_blank">on-projects</a></p></div>
</div>
</section>
<?php include("sidebar.php") ?>
<?php include("footer.php") ?>
</div>
</body>
</html>
<file_sep>/School_Website/settings2.php
<meta charset="utf-8">
<?php
include('session.php');
$_SESSION['pageStore'] = "setting.php";
if(!isset($_SESSION['index_id'])){
header("location: index.php"); // Redirecting To login
}
<br>'
. $session_fullName
. '<br>
<script type="text/javascript">
function init() {
document.getElementById("button")
.addEventListener("click", warnung);
}
function warnung() {
var check = confirm("Wollen sie ihren Account wirklich Löschen?");
if (check == true) {
window.location = "/destroyer.php";
}
if (check == false) {
window.location = "/setting.php";
}
document.addEventListener("DOMContentLoaded", init);
</script>
<a href="logout.php">Ausloggen</a>
</div>';
?>
<file_sep>/School_Website/programms.php
<?php include("meta.php") ?>
<?php include("header.php") ?>
<section>
<div class="article">
<img src="Bilder/vorschau.png" alt="Vorschau">
<a href="#">Hitfilm</a>
<p>Hitfilm ist ein super cooles und einfach zu verstehendes kostenloses Schnitt Programm. Perfekt für Anfänger. <br> Achtung!: Nur auf Englisch.</p>
</div>
<div class="article">
<img src="Bilder/vorschau.png" alt="Vorschau">
<a href="#">Windows Movie Maker</a>
<p>Windows Movie Maker ist ein sehr einfaches und gut zu verstehendes Schnitt Programm <br> Kostenlos </p>
</div>
<div class="article">
<img src="Bilder/vorschau.png" alt="Vorschau">
<a href="#">Adobe Premiere Pro</a>
<p>Adobe Premiere Pro ist ein sehr umfangreiches, aber trotzdem einfach zu verstehendes Schnitt Programm. Perfekt für Unternehmen und Youtuber. <br>Achtung!: Kostet Monatlich</p>
</div>
<div class="article">
<img src="Bilder/vorschau.png" alt="Vorschau">
<a href="#">Adobe Premiere Elements</a>
<p>Adobe Premiere Elements ist ein sehr einfaches, aber kompaktes Schnitt Programm. Perfekt für Familienfilme. <br>Achtung!: Kostet ca. 30-40€</p>
</div>
<div class="article">
<img src="Bilder/vorschau.png" alt="Vorschau">
<a href="#">Adobe After Effects</a>
<p>Adobe After Effects ist ein sehr umfassendes 2D und 3D motion VFX Programm, mit welchem man komplizierte Effekte einfach erstellen und bearbeiten kann. <br>Achtung!: Kostet Monatlich </p>
</div>
<div class="article">
<img src="Bilder/vorschau.png" alt="Vorschau">
<a href="#">Adobe Photoshop</a>
<p>Adobe Photoshop ist ein sehr weitläufiges 2D und 3D motion Grafik Desing Programm, mit welchem man jedes Bild in ein Meisterwerk verwandeln kann, auch wunderbar Zeichnen und "Malen" <br> Achtung!: Kostet Monatlich </p>
</div>
<div class="article">
<img src="Bilder/vorschau.png" alt="Vorschau">
<a href="#">Gimp</a>
<p>Gimp ist ein sehr umfanssendes Grafik Programm, welches perfekt für Schulen und Universitäten ist. <br> Kostenlos </p>
</div>
<div class="article">
<img src="Bilder/vorschau.png" alt="Vorschau">
<a href="#">Paint.net</a>
<p>Paint.net ist ein einfaches Grafik Programm, welches perfekt für Schulen und Familien ist. <br> Kostenlos </p>
</div>
<div class="article">
<img src="Bilder/vorschau.png" alt="Vorschau">
<a href="#">Blender</a>
<p>Blender ist ein sehr umfanssendes 3D motion Desing Programm, mit welchem man, super coole 3D Objekte erstellen kann. <br> Kostenlos </p>
</div>
</section>
<?php include("sidebar.php") ?>
<?php include("footer.php") ?>
<file_sep>/School_Website/register.php
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
if(isset($_SESSION['login_id'])) {
header("location: account.php"); // Redirecting To Profile
}
//Register progess start, if user press the signup button
if (isset($_POST['signUp'])) {
if (empty($_POST['fullName']) || empty($_POST['email']) || empty($_POST['newPassword'])) {
$fehlermeldung = "Please fill up all the required field.";
} else {
$fullName = $_POST['fullName'];
$email = $_POST['email'];
$password = $_POST['newPassword'];
$hash = password_hash($password, PASSWORD_DEFAULT);
// Make a connection with MySQL server.
include('config.php');
$sQuery = "SELECT id from account where email=? LIMIT 1";
$iQuery = "INSERT Into account (fullName, email, password) values(?, ?, ?)";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($sQuery);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_result();
$rnum = $stmt->num_rows;
if($rnum==0) { //if true, insert new data
$stmt->close();
$stmt = $conn->prepare($iQuery);
$stmt->bind_param("sss", $fullName, $email, $hash);
if($stmt->execute()) {
$fehlermeldung = 'Du wurdest erfolgreich regestriert, bitte logge dich jetzt mit deinen Daten ein.';}
} else {
$fehlermeldung = 'Diese E-mail hat schon ein anderer User.';
}
$stmt->close();
$conn->close(); // Closing database Connection
}
}
?>
<!DOCTYPE html>
<html>
<?php include("meta.php") ?>
<head>
<?php include("header.php") ?>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Register</title>
<link rel="stylesheet" href="auth.css">
</head>
<body>
<div class="rlform">
<div class="rlform rlform-wrapper">
<div class="rlform-box">
<div class="rlform-box-inner">
<form method="post" oninput='validatePassword()'>
<p>Kreiere deinen Account</p>
<div class="rlform-group">
<label>Name</label>
<input type="text" name="fullName" class="rlform-input" required>
</div>
<div class="rlform-group">
<label>E-mail</label>
<input type="email" name="email" class="rlform-input" required>
</div>
<div class="rlform-group">
<label>Passwort</label>
<input type="<PASSWORD>" name="newPassword" id="newPass" class="rlform-input" required>
</div>
<div class="rlform-group">
<label>Bestätige das Passwort</label>
<input type="<PASSWORD>" name="conformpassword" id="conformPass" class="rlform-input" required>
</div>
<button class="rlform-btn" name="signUp">Sign Up
</button>
<div class="text-foot">
Du hast schon einen Account? <a href="form.php">Login</a>
</div>
</form>
</div>
</div>
</div>
</div>
<?php include("footer.php") ?>
<script>
function validatePassword(){
if(newPass.value != conformPass.value) {
conformPass.setCustomValidity('Die Passwörter stimmen nicht überein');
} else {
conformPass.setCustomValidity('');
}
}
</script>
</body>
</html>
<file_sep>/School_Website/session.php
<?php
// Make connection with database
include('config.php');
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
if (isset($_SESSION['login_id'])) {
$user_id = $_SESSION['login_id'];
$Squery = "SELECT fullName from account where id = ? LIMIT 1";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($Squery);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($fullName);
$stmt->store_result();
if($stmt->fetch()) //fetching the contents of the row
{
$session_fullName = $fullName;
$stmt->close();
$conn->close();
}
}
?>
<file_sep>/School_Website/index.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<?php include("meta.php") ?>
<body>
<?php include("header.php") ?>
<section>
<div class="article">
<img src="Bilder/vorschau.png" alt="Vorschau">
<a href="#">Willkommen auf unserer Schulwebseite!</a>
<p>Melde dich mit deinen Zugangsdaten an um auf unseren eigenen Vertretungsplan zuzugreifen. </p>
</div>
<div class="article">
<img src="Bilder/vorschau.png" alt="pepe">
<a href="">Das ist der Titel von diesem Beitrag</a>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
sed diam voluptua. </p>
</div>
<div class="article">
<img src="Bilder/vorschau.png" alt="Vorschau">
<a href="#">Das ist der Titel von diesem Beitrag</a>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
sed diam voluptua. </p>
</div>
</section>
<?php include("sidebar.php") ?>
<?php include("footer.php") ?>
</div>
</body>
</html>
<file_sep>/School_Website/login.php
<?php
session_start(); // Starting Session
//if session exit, user nither need to signin nor need to signup
if(isset($_SESSION['login_id'])){
if (isset($_SESSION['pageStore'])) {
$pageStore = $_SESSION['pageStore'];
header("location: $pageStore"); // Redirecting To Profile Page
}
}
//Login progess start, if user press the signin button
if (isset($_POST['signIn'])) {
if (empty($_POST['fullName']) || empty($_POST['password'])) {
echo "Username oder Password sind Falsch";
}
else
{
$name = $_POST['fullName'];
$password = $_POST['password'];
// Make a connection with MySQL server.
include('config.php');
$sQuery = "SELECT id, password from account where fullName=? LIMIT 1";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($sQuery);
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($id, $hash);
$stmt->store_result();
if($stmt->fetch()) {
if (password_verify($password, $hash)) {
$_SESSION['login_id'] = $id;
if (isset($_SESSION['pageStore'])) {
$pageStore = $_SESSION['pageStore'];
}
else {
$pageStore = "account.php";
}
header("location: $pageStore"); // Redirecting To Profile
$stmt->close();
$conn->close();
}
else {
echo 'Username oder Password sind Falsch';
}
} else {
echo 'Username oder Password sind Falsch';
}
$stmt->close();
$conn->close(); // Closing database Connection
}
}
?>
<file_sep>/School_Website/destroyer.php
<?php
session_start();
include('session.php');
$_SESSION['pageStore'] = "setting.php";
if(!isset($_SESSION['login_id'])){
header("location: form.php.php");
}
$Squery = "DELETE from account where id = ? LIMIT 1";
include('config.php');
$stmt = $conn->prepare($Squery);
$stmt->bind_param("i", $_SESSION['login_id']);
$stmt->execute();
if(session_destroy())
{
header("Location: form.php"); // Redirecting To Home Page
}
?>
<file_sep>/School_Website/header.php
<script src="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js" data-cfasync="false"></script>
<script>
window.cookieconsent.initialise({
"palette": {
"popup": {
"background": "#000"
},
"button": {
"background": "#f1d600"
}
},
"content": {
"message": "Bitte akteptieren Sie die Cookies um auf die Webseite weitergeleitet zu werden.",
"dismiss": "Ok ",
"link": "Mehr",
"href": "imprint.php"
}
});
</script>
<div id="wrapper">
<header><img src="Bilder/Logo2.0.png" alt="Logo"></header>
<?php include('session.php'); ?>
<nav>
<ul>
<li><a href="index.php"style="color">Home</a></li>
<li><a href="vp.php">Vertretungsplan</a></li>
<li><a href="contact.php">Kontakte</a></li>
<?php
if (isset($session_fullName)) {
echo "<li><a href=\"account.php\">Profil</a></li>";
} else {
echo '<li><a href="form.php">Anmelden</a></li>';
}
?>
</ul>
</nav>
<div class="fehlermeldung">
<?php
if (isset($fehlermeldung)) {
echo $fehlermeldung;
}
?>
</div>
<file_sep>/School_Website/imprint.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<?php include("meta.php") ?>
<body>
<?php include("header.php") ?>
<section2>
<div id="Impressum">
<h1>Impressum</h1>
<p>Informationspflicht laut § 5 TMG.<br><br>
TwentyE & Chilldor <br>
Leipzig <br>
Deutschland <br>
</div>
</section2>
<?php include("footer.php") ?>
</div>
</body>
</html>
<file_sep>/School_Website/setting.php
<meta charset="utf-8">
<?php
include('session.php');
$_SESSION['pageStore'] = "setting.php";
if(!isset($_SESSION['login_id'])){
header("location: login.php"); // Redirecting To login
}
echo '<div style="font-size: 35px;">
<strong>Einstellungen</strong>
<br>'
. $session_fullName
. '<br>
<script type="text/javascript">
function init() {
document.getElementById("button")
.addEventListener("click", warnung);
}
function warnung() {
var check = confirm("Wollen sie ihren Account wirklich Löschen?");
if (check == true) {
window.location = "/destroyer.php";
}
if (check == false) {
window.location = "/setting.php";
}
document.addEventListener("DOMContentLoaded", init);
</script>
<a id="button" href="destroyer.php">Account Löschen</a>
<br>
<a href="index.php">Profil</a>
<a href="logout.php">Ausloggen</a>
</div>';
?>
<file_sep>/School_Website/form.php
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
if(isset($_SESSION['login_id'])) {
header("location: account.php"); // Redirecting To Profile
}
//echo "test";
//Login progess start, if user press the signin button
if (isset($_POST['signIn'])) {
if (empty($_POST['fullName']) || empty($_POST['password'])) {
echo "Username oder Password sind Falsch";
} else {
$name = $_POST['fullName'];
$password = $_POST['password'];
include('config.php');
$sQuery = "SELECT id, password from account where fullName=? LIMIT 1";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($sQuery);
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($id, $hash);
$stmt->store_result();
if($stmt->fetch()) {
if (password_verify($password, $hash)) {
$_SESSION['login_id'] = $id;
header("location: account.php"); // Redirecting To Profile
$stmt->close();
$conn->close();
} else {
echo 'Username oder Password sind Falsch';
}
} else {
echo 'Username oder Password sind Falsch';
}
$stmt->close();
$conn->close(); // Closing database Connection
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<?php include("meta.php") ?>
<body>
<?php include("header.php") ?>
<div class="rlform">
<div class="rlform rlform-wrapper">
<div class="rlform-box">
<div class="rlform-box-inner">
<form method="post">
<p>Melde dich an um Fortzufahren</p>
<div class="rlform-group">
<label>Benutzername</label>
<input type="fullName" name="fullName" class="rlform-input" required>
</div>
<div class="rlform-group password-group">
<label>Passwort</label>
<input type="<PASSWORD>" name="password" class="rlform-input" required>
</div>
<button type="submit" class="rlform-btn" name="signIn">Sign In
</button>
</form>
</div>
</div>
</div>
</div>
<?php include("footer.php") ?>
</div>
</body>
</html>
|
392586bd0e68b277dbdbb11487b23241ea3463d5
|
[
"Markdown",
"PHP"
] | 17
|
PHP
|
TwentyE/Schulwebsite_By_J_L
|
e09bfd21586580a84b6cc2aa28f8b942b55bdc4d
|
a008cc49e35e4eddb71ae03b1fb73db7e6062b26
|
refs/heads/master
|
<repo_name>antonybstack/CGWebsite<file_sep>/stattracker.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Carolina Gaming - CodMW Lookup</title>
<meta name="description" content="Carolina Gaming Website">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <!-- jquery dependency -->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="script.js"></script>
<!-- slick dependencies -->
<link rel="stylesheet" type="text/css" href="slick-1.8.1/slick/slick.css" />
<link rel="stylesheet" type="text/css" href="slick-1.8.1/slick/slick-theme.css" />
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="slick-1.8.1/slick/slick.min.js"></script>
</head>
<!-- viewable webpage begins -->
<body>
<!-- Navigational Bar -->
<nav class="nav-header">
<!-- uses tilt.js plugin-->
<div class="nav-logo" data-tilt data-tilt-reverse="true" data-tilt-scale="1.1" data-tilt-glare data-tilt-max-glare="0.05" data-tilt-max="7">
<a class="link" href="index.html"><img id="cdlogo" alt="cglogo" src="images/cglogo.png" width="100"></a>
</div>
<div class="nav-header-links">
<ul class="parent">
<li class="header-item"><a class="link" href="index.html">Home</a></li>
<li class="header-item"><a class="link" href="about.html">About Us</a></li>
<li class="header-item"><a class="link-active" href="stattracker.html">Cod MW Stats</a></li>
<li class="header-item"><a class="link" href="teammates.html">Teammates</a></li>
<li class="header-item"><a class="link" href="contact.html">Contact Us</a></li>
</ul>
</div>
</nav>
<main>
<div class="home-container">
<div id="codstats">
<div id="titleBlock">
<p id="codTitle">Call of Duty Modern Warfare Player Stat Lookup</p>
</div>
<!-- form allows user to input account name to lookup -->
<form id="target" action="destination.html">
<div id="radioButtons">
<div class>
<input type="radio" id="xbox" name="drone" value="xbox">
<label for="xbox">Xbox</label>
</div>
<div>
<input type="radio" id="psn" name="drone" value="psn">
<label for="psn">PSN</label>
</div>
<div>
<input type="radio" id="pc" name="drone" value="pc">
<label for="pc">PC</label>
</div>
<div id="inputArea">
</div>
</div>
</form>
<div id="data"></div>
</div>
</div>
</main>
<footer>
<div class="footer-container">
<!-- First Column of Footer - 'About' -->
<div class="footers">
<h3>About Carolina Gaming</h3>
Carolina Gaming is a new era esports and online entertainment brand representing the carolinas.
Build on the shoulders of persistency, Carolina Gaming has established itself as the preeminent
brand respresenting both North Carolina, and South Carolina, in the esports industry. Carolina
Gaming, founded in 2018 by Bryson "<NAME>, has taken part in numberous events and
tournments, invested heavily into the careers of players and creators who dawn the carolina logo,
and given back to the many community members and fans. Moving forward, our goals are to bring
Carolinas a major esports franchise, build a headquarters in Charlotte, North Carolina, win
championships, and tell the best stories in online entertainm,ent. We want to continue building
a reputatble brand in the Carolinas and finally give it the recognition in esports that it deserves.
</div>
<!-- Second Column of Footer - 'Site Links' -->
<div class="footers">
<h3>Site Links</h3>
<nav class="nav-footer">
<ul>
<li class="footer-item"><a class="link" href="index.html">Home</a></li>
<li class="footer-item"><a class="link" href="about.html">About Us</a></li>
<li class="footer-item"><a class="link" href="stattracker.html">Cod MW Stats</a></li>
<li class="footer-item"><a class="link" href="teammates.html">Teammates</a></li>
<li class="footer-item"><a class="link" href="contact.html">Contact Us</a></li>
</ul>
</nav>
</div>
<!-- Third Column of Footer - 'Social Media' -->
<div class="footers">
<h3>Social Media</h3>
<nav class="nav-footer">
<ul>
<li class="footer-item"><a class="link" href="https://twitter.com/thecarolinagg?lang=en">Twitter</a></li>
<li class="footer-item"><a class="link" href="https://www.youtube.com/channel/UCvFHCR-xSQRm4GtQNh8k0eg">Youtube</a></li>
<li class="footer-item"><a class="link" href="https://discordapp.com/invite/BJ8T24M">Discord</a></li>
<li class="footer-item"><a class="link" href="https://www.twitch.tv/team/ember">Twitch</a></li>
<li class="footer-item"><a class="link" href="https://www.instagram.com/thecarolinagg/">Instagram</a></li>
</ul>
</nav>
</div>
</div>
<!-- Validation -->
<div class="validation">
<p class="rights">©2019 <NAME>. All rights reserved.</p>
<a href="https://validator.w3.org/check?uri=referer">Validate HTML</a>
<a href="https://jigsaw.w3.org/css-validator/check/referer">Validate CSS</a>
</div>
</footer>
<!--tilt.js plugin-->
<script src="vanilla-tilt.js"></script>
</body>
</html>
<file_sep>/README.md
# CGWebsite
This is my web app I have been developing for the past semester. I developed this for my client <NAME>. He is my roomate who owns an esports company, and needed a website to represent his company. The website presents information to any user interested in learning more about his esports company.
Link to website
https://webpages.uncc.edu/ablyakhe/Exercise/CGWebsite/index.html
* Interactivity
* 1 Jquery UI widget
Used the jQuery UI ‘Accordion’ widget which is used to group content into separate panels that can be open or closed based on interaction from user end.
* 2 query Plugins
Carousel jQuery plugin called ‘Slick’. A slideshow of images infinitely loops through, and the user has an option to click through them too.
A parallax hover tilt effect jQuery plugin called ‘Tilt.js’. It is responsive to the user’s mouse movement and animates a container to move as the user hovers over it with their mouse.
* 2 Ajax requests
An api call using Ajax request, which GETs data about an xbox, ps4, or pc player on Call of Duty Modern Warfare, and displays statistics about their player account.
An api call using Ajax request which GETs images/gifs from a json file stored locally.
## Video Demo [](https://youtu.be/26xRbalSWjU)
<file_sep>/script.js
// using 2 jquery Widget effects
$(document).ready(function() {
$("#t").hover(
function() {
$(this).find('ul>li').show(300);
},
function() {
$(this).find('ul>li').hide(600);
}
);
// jQuery Carousal 'Slick' plugin for home page
if ($(".slideshow").length) {
$('.slideshow').slick({
infinite: true,
speed: 500,
fade: true,
cssEase: 'linear',
adaptiveHeight: true,
autoplay: true,
autoplaySpeed: 2500
});
}
// jQuery UI Widget for teammates page
if ($("#accordion").length) {
$('#accordion').accordion({
active: false,
collapsible: true
});
}
//whenever radio button is clicked, the necessary input elements are populated to the form based on the platform selected
$("input[id='xbox']").change(function() {
var htmlXbox = "";
htmlXbox += "gamertag: <input id='gamertag' type='text' name='gamertag' value='m45pro'><br>";
htmlXbox += "<input id='sub' type='submit' value='Submit'><br>";
$("#inputArea").html(htmlXbox);
});
$("input[id='psn']").change(function() {
var htmlXbox = "";
htmlXbox += "gamertag: <input id='gamertag' type='text' name='gamertag' value='reidboyy'><br>";
htmlXbox += "<input id='sub' type='submit' value='Submit'><br>";
$("#inputArea").html(htmlXbox);
});
$("input[id='pc']").change(function() {
var htmlXbox = "";
htmlXbox += "gamertag: <input id='gamertag' type='text' name='gamertag' value='Gorapter5'>";
htmlXbox += "#<input id='blizzardtag' type='text' name='blizzardtag' value='1216'><br>";
htmlXbox += "<input id='sub' type='submit' value='Submit'><br>";
$("#inputArea").html(htmlXbox);
});
//takes input from user and populates gamertag
$('#target').submit(function(event) {
event.preventDefault();
if (document.getElementById("pc").checked) {
var gamertag = $('#gamertag').val();
var blizzardtag = $('#blizzardtag').val();
gamertag = gamertag + "%23" + blizzardtag; //combines gamertag and blizzardtag, %23 is added between for the api call
} else {
var gamertag = $('#gamertag').val();
}
//determines the specific api to use based on the platform radio buttons
if (document.getElementById("xbox").checked) {
// xbox
var url = 'https://my.callofduty.com/api/papi-client/stats/cod/v1/title/mw/platform/xbl/gamer/' + gamertag + '/profile/type/mp';
} else if (document.getElementById("pc").checked) {
// pc
var url = 'https://my.callofduty.com/api/papi-client/stats/cod/v1/title/mw/platform/battle/gamer/' + gamertag + '/profile/type/mp';
} else if (document.getElementById("psn").checked) {
// pc
var url = 'https://my.callofduty.com/api/papi-client/stats/cod/v1/title/mw/platform/psn/gamer/' + gamertag + '/profile/type/mp';
}
var html = ""; //create variable to hold all html that is created in the ajax function
// ajax request #1 call of duty api
$.ajax({
type: 'POST',
url: url,
beforeSend: function() {
$("#data").html("Loading...");
},
timeout: 10000,
error: function(xhr, status, error) {
alert("Error: " + xhr.status + " - " + error);
},
dataType: "json",
success: function(data) {
html += "<p class='datap'>Username: </p><p class='dataItem'>" + data.data.username + "</p><br>";
html += "<p class='datap'>Level: </p><p class='dataItem'>" + data.data.level + "</p><br>";
html += "<p class='datap'>kdRatio: </p><p class='dataItem'>" + data.data.lifetime.all.properties.kdRatio.toFixed(2) + "</p><br>";
html += "<p class='datap'>Score Per Game: </p><p class='dataItem'>" + data.data.lifetime.all.properties.scorePerGame.toFixed(2) + " points</p><br>";
html += "<p class='datap'>Win Rate: </p><p class='dataItem'>" + ((data.data.lifetime.all.properties.wins / (data.data.lifetime.all.properties.wins + data.data.lifetime.all.properties.losses)).toFixed(2)) + "%</p><br>";
html += "<p class='datap'>headshot rate: </p><p class='dataItem'>" + (data.data.lifetime.all.properties.headshots / data.data.lifetime.all.properties.kills).toFixed(2) + "%</p><br>";
html += "<p class='datap'>bestKillStreak: </p><p class='dataItem'>" + data.data.lifetime.all.properties.bestKillStreak + "</p>";
$("#data").html(html);
}
});
});
// ajax request #2 file retrieval
$.ajax({
url: 'images.json',
dataType: 'json',
success: function(data) {
console.log(data.images[0].image);
html = "<img src=" + data.images[2].image + " alt=" + data.images[2].image + " height=100px>";
$("#data").html(html);
},
statusCode: {
404: function() {
alert('There was a problem with the server. Try again soon!');
}
}
});
}); //end ready
|
5ddc4db0223c62ae3c884d8ea2cf99afea5e9a14
|
[
"Markdown",
"JavaScript",
"HTML"
] | 3
|
HTML
|
antonybstack/CGWebsite
|
99781fe2f539468a17766629c75e11130ca622fa
|
4a45f591b826b34b365b6dc83f81ea48519257b3
|
refs/heads/master
|
<file_sep>/*
* Name: <NAME>
* Login: cs8bagf
* Date: 2/22/12
* File: ResizableBallController.java
* Sources of Help: google, TA
*
* This program creates a horizontal and vertical line which intersect.
The user is able to drag around the lines upon clicking and dragging.
Each actionevent has a method that defines the users
actions(click,drag etc). This also creates 3 buttons in start,slow,clear.
Also creates a slider used to control the resizing speeds of the balls.
*/
import objectdraw.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/*
* Name: ResizableBallController extends WindowController
implements ActionListener,ChangeListener,MouseListener,
MouseMotionListener.
* Purpose: This class contains all of the methods that enable
this program to work. This class extends WindowController which
allows the programmer to use methods reserved for only
WindowController.
* Parameters: none
* Return: none
*/
public class ResizableBallController extends WindowController implements ActionListener, ChangeListener, MouseListener, MouseMotionListener
{
private Line h_line, v_line;
private double widthVar, heightVar;
private double width, height;
private ResizableBall ballImage;
private boolean h_grabbed, v_grabbed;
private static final int MIN_SPEED = 1,
MAX_SPEED = 100,
PAUSE = 50;
private JSlider speedSlider;
private JButton startButton,
stopButton,
clearButton;
private JLabel speedLabel,
titleLabel;
private int speed = PAUSE;
/*
* Name: begin()
* Purpose: Creates the lines and indicates their locations.
Creates the buttons, title text, and creates the slider.
Adds them using action listener.
* Parameters: None
* Return: void
*/
public void begin(){
//creates panels
JPanel buttonPanel = new JPanel();
JPanel titlePanel = new JPanel();
JPanel northPanel = new JPanel();
JPanel southPanel = new JPanel();
//sets layout and text
titleLabel = new JLabel("Resizable Ball Controls");
northPanel.setLayout(new GridLayout(2,3));
//creates buttons
startButton = new JButton("Start");
stopButton = new JButton("Stop");
clearButton = new JButton("Clear All");
//adds actionListener
startButton.addActionListener(this);
stopButton.addActionListener(this);
clearButton.addActionListener(this);
//adds the labels and panels
titlePanel.add(titleLabel);
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
buttonPanel.add(clearButton);
northPanel.add(titlePanel);
northPanel.add(buttonPanel);
this.add(northPanel, BorderLayout.NORTH);
this.validate();
//speed
speedLabel = new JLabel
("Use the slider to adjust the speed");
speedSlider = new JSlider(JSlider.HORIZONTAL,
MIN_SPEED, MAX_SPEED, PAUSE);
southPanel.add(speedLabel);
southPanel.add(speedSlider);
speedSlider.addChangeListener(this);
Container contentPane = getContentPane();
contentPane.add( southPanel, BorderLayout.SOUTH );
contentPane.validate();
//sets variables
widthVar = 0.5;
heightVar = 0.5;
//creates new lines
v_line = new Line(0,heightVar*height,
width,heightVar*height,canvas);
h_line = new Line(widthVar*width,0,
widthVar*width,height,canvas);
canvas.addMouseListener(this);
canvas.addMouseMotionListener(this);
}
/*
* Name: onMouseClick
* Purpose: It calls the ResizableBall class
* Parameters: Location point (Location of the click)
* Return: void
*/
public void mouseClicked(MouseEvent evt){
//calls resizableball class
ballImage = new ResizableBall
(evt.getX(), evt.getY(), 50, canvas,
h_line, v_line, speed);
speedSlider.addChangeListener(ballImage);
startButton.addActionListener(ballImage);
stopButton.addActionListener(ballImage);
clearButton.addActionListener(ballImage);
canvas.addMouseListener(ballImage);
canvas.addMouseMotionListener(ballImage);
}
public void mouseEntered(MouseEvent evt){}
public void mouseExited(MouseEvent evt){}
/*
* Name: stateChanged
* Purpose: Sets the speed for resizing the balls.
* Parameters: ChangeEvent evt (When the state occurs).
* Return: void
*/
public void stateChanged(ChangeEvent evt){
speed = speedSlider.getValue();
if(ballImage != null){
ballImage.setSpeed(speed);
}
speedLabel.setText("The speed is " + speed);
}
public void actionPerformed(ActionEvent evt){}
/*
* Name: onMousePress
* Purpose: Creates grabbed variables and click awareness.
* Parameters: Point(Location of the click).
* Return: void
*/
public void mousePressed(MouseEvent evt){
//Checks if the Location point lies on the h_line
//and creates variable h_grabbed.
h_grabbed = h_line.contains
(new Location(evt.getPoint()));
//Checks if the Location point lies on the y_line
v_grabbed = v_line.contains
(new Location(evt.getPoint()));
}
/*
* Name: onMouseDrag
* Purpose: States if conditions checking if the line is within limits.
This also causes the line to be dragged.
* Parameters: Point (location of the click)
* Return: Specify the return type and what it represents.
* If no return value, just specify void.
*/
public void mouseDragged(MouseEvent evt){
//Drags the h_line if it is pressed.
if(h_grabbed){
if((evt.getY() >= 5) && (evt.getY() <= height - 5)){
heightVar = evt.getY() / height;
h_line.setEndPoints(0, heightVar * height, width, heightVar * height);
}
//makes sure the h_line does not get too close to the top border
else if(evt.getY() < 5){
h_line.setEndPoints(0, 5, width, 5);
heightVar = 5 / height;
}
//makes sure the h_line does not get too close to the bottom border
else{
h_line.setEndPoints(0, height - 5, width, height - 5);
heightVar = (height - 5) / height;
}
}
//Drags the v_line if it is pressed
if(v_grabbed){
if((evt.getX() >= 5) && (evt.getX() <= width - 5)) {
widthVar = evt.getX() / width;
v_line.setEndPoints(widthVar * width, 0, widthVar * width, height);
}
//makes sure the v_line does not get too close to the left border
else if(evt.getX() < 5){
v_line.setEndPoints(5, 0, 5, height);
widthVar = 5 / width;
}
//makes sure the v_line does not get too close to the right border
else{
v_line.setEndPoints(width - 5, 0, width - 5, height);
widthVar = (width - 5) / width;
}
}
}
public void mouseMoved(MouseEvent evt){}
public void mouseReleased(MouseEvent evt){}
/*
* Name: paint()
* Purpose: Resets and shifts lines
* Parameters: java.awt.Graphics g(imported graphics)
* Return: void
*/
public void paint(java.awt.Graphics g){
super.paint(g);
//reset width and height
width = canvas.getWidth();
height = canvas.getHeight();
//shift lines
h_line.setEndPoints(0, heightVar * height, width, heightVar * height);
v_line.setEndPoints(widthVar * width, 0, widthVar * width, height);
}
}
<file_sep>/*
* Name: <NAME>
* Login: cs8bagf
* Date: 2/22/12
* File: ResizableBall.java
* Sources of Help: google, TA
*
* This program creates the balls and causes them to grow and
shrink after a user click. This gives the balls color according
to which quadrant they reside in. There is also adjustment to
resizing the window and moving around the lines.If the buttons
are pressed then they will react according to their purpose.
*/
import objectdraw.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/*
* Name: ResizableBall extends ActiveObject implements
MouseListener,ChangeListener,ActionListener.
* Purpose: Creates a ctor, and run() method. Each has its
own function that contributes to the overall program. Extends ActiveObject
which enables the run method.Creates constants.
* Parameters: none
* Return: none
*/
public class ResizableBall extends ActiveObject implements
MouseListener,MouseMotionListener, ChangeListener, ActionListener
{
//creates the ball
private FilledOval ball;
//variables for resizing and pause
private static final double MAX_SIZE = 100,
GROWTH = 2,
PAUSE = 50,
MIN_SIZE = 50;
//center x & y location
double cxLoc,cyLoc;
//the size
double size = 50;
//used for canvas
private DrawingCanvas canvas;
//used to initialize lines
private Line hLine,
vLine;
//speed
private int speed;
//condition for run()
private boolean b_grabbed,
grow = true;
//used for calling buttons
private JButton startButton,
stopButton,
clearButton;
private JSlider speedSlider;
//ResizableBall ctor
/*
* Name: ResizableBall
* Purpose: Implements color checks and uses parameters.
* Parameters: xLoc&yLoc(used to find center coordinates),
size(indicator of color),canvas(the "world),hLine&vLine(The lines),
initspeed(used for speed).
(uses actions on click).
* Return: none
*/
public ResizableBall(double xLoc, double yLoc, double size,
DrawingCanvas aCanvas, Line hLine, Line vLine, int initSpeed){
canvas = aCanvas;
this.hLine = hLine;
this.vLine = vLine;
//finds center location
cxLoc = xLoc - size / 2;
cyLoc = yLoc - size / 2;
ball = new FilledOval(cxLoc, cyLoc, size, size, canvas);
speed = initSpeed;
start();
}
/*
* Name: changeColor()
* Purpose: Changes balls according to quadrant
* Parameters: none
* Return: void
*/
public void changeColor()
{
//set initial color of top left quadrant
if((cxLoc < vLine.getStart().getX()) &&
(cyLoc < hLine.getStart().getY())){
ball.setColor(Color.cyan);
}
//set initial color of top right quadrant
if((cxLoc > vLine.getStart().getX()) &&
(cyLoc < hLine.getStart().getY())){
ball.setColor(Color.magenta);
}
//set initial color of bottom left quadrant
if((cxLoc < vLine.getStart().getX()) &&
(cyLoc > hLine.getStart().getY())){
ball.setColor(Color.yellow);
}
//set initial color of bottom right quadrant
if((cxLoc > vLine.getStart().getX()) &&
(cyLoc > hLine.getStart().getY())){
ball.setColor(Color.black);
}
}
/*
* Name: mouseClicked
* Purpose: If mouse is clicked.
* Parameters: evt
* Return: void
*/
public void mouseClicked(MouseEvent evt){}
/*
* Name: mouseEntered
* Purpose: If mouse enters.
* Parameters: evt
* Return: void
*/
public void mouseEntered(MouseEvent evt){}
/*
* Name: mouseExited
* Purpose: If mouse exits.
* Parameters: evt
* Return: void
*/
public void mouseExited(MouseEvent evt){}
/*
* Name: stateChanged
* Purpose: Changes speed
* Parameters: ChangeEvent evt
* Return: void
*/
public void stateChanged(ChangeEvent evt){
//get the JSlider value
speed = ((JSlider)(evt.getSource())).getValue();
}
/*
* Name: actionPerformed
* Purpose: Conditions depending on whether
buttons are pressed.
* Parameters: evt
* Return: void
*/
public void actionPerformed(ActionEvent evt){
//if start is pressed, activate run method
if(evt.getActionCommand().equals("Start")){
start();
}
//if stop is pressed, stop all of the balls
//and change color.
if(evt.getActionCommand().equals("Stop")){
stop();
changeColor();
}
//if clear all is pressed, clear all of the balls
//from the canvas.
if(evt.getActionCommand().equals("Clear All")){
ball.removeFromCanvas();
}
}
/*
* Name: mousePressed
* Purpose: Conditions depending on whether
buttons are pressed.
* Parameters: evt
* Return: void
*/
public void mousePressed(MouseEvent evt){
//Checks if the MouseEvent evt lies on the ball
//and creates variable b_grabbed.
b_grabbed = ball.contains
(new Location(evt.getPoint()));
}
/*
* Name: mouseDragged
* Purpose: checks to see if the ball
contains an evt.
* Parameters: evt
* Return: void
*/
public void mouseDragged(MouseEvent evt){
if(b_grabbed){}
}
/*
* Name:mouseMoved
* Purpose: If mouse moved.
* Parameters: evt
* Return: void
*/
public void mouseMoved(MouseEvent evt){}
/*
* Name: mouseReleased
* Purpose: If mouse released.
* Parameters: evt
* Return: void
*/
public void mouseReleased(MouseEvent evt){}
/*
* Name: setSpeed()
* Purpose: Creates setSpeed method
for slider use.
* Parameters: newSpeed
* Return: void
*/
public void setSpeed(int newSpeed)
{
speed = newSpeed;
}
/*
* Name: resizeBall()
* Purpose: resizes the ball
* Parameters: none
* Return: void
*/
public void resizeBall(){
//if it grows set xLoc, YLoc and
//increment, otherwise false.
if(grow){
if(size < MAX_SIZE){
double xLoc = cxLoc + size/2;
double yLoc = cyLoc + size/2;
size += GROWTH;
ball.setSize(size, size);
cxLoc = xLoc - size / 2;
cyLoc = yLoc - size / 2;
ball.moveTo(cxLoc, cyLoc);
}else{
grow = false;
}
}else{
//otherwise shrink
if((size <= MAX_SIZE) && (size > MIN_SIZE)){
double xLoc = cxLoc + size/2;
double yLoc = cyLoc + size/2;
size -= GROWTH;
ball.setSize(size, size);
cxLoc = xLoc - size / 2;
cyLoc = yLoc - size / 2;
ball.moveTo(cxLoc, cyLoc);
}else{
grow = true;
}
}
//time delay to prevent lag
pause(100 - speed);
}
/*
* Name: run()
* Purpose: Calls changeColor, creates a infinite loop
* that shrinks and grows the balls. This also centers the
* area where the ball grows.
* Parameters: none
* Return: void
*/
public void run(){
//infinite loop
while(true){
changeColor();
resizeBall();
}
}
}
|
dbd2b2ea36deddea487558070497594dbdd6e6b3
|
[
"Java"
] | 2
|
Java
|
DrivenBlue/ResizableBall
|
c5548398d5fefa12f168dc1b1bc0c45e2a09c54f
|
933077c16fe341f01043a6486312c5b71a1e6d79
|
refs/heads/master
|
<file_sep># Docs Equations Calculator
Work in Progress.
## Goals:
As a user, I can:
- [ ] compute mathematical expressions such as `1+2` without leaving Docs
- [ ] compute more complicated expressions that involve simple math functions such as fractions, square roots, logarithms, exponents, etc.
- [ ] compute sums, products, integrals
- [ ] verify that the system is computing the expression I want it to compute
- [ ] recompute existing calculations if I change one part of the expression
- [ ] represent the answer as a fraction or decimal
- [ ] represent the variable in terms of variables
- [ ] represent the answer in terms of pi, e, or other constants
Implementation plan:
- [x] convert Docs Equation to LaTeX and show expression in box
- [ ] compute answer using existing software. Ideas:
- [Wolfram Alpha](https://products.wolframalpha.com/api/libraries/javascript/) (preferred because it's symbolic)
- [Evaluatex](https://arthanzel.github.io/evaluatex/)
- [ ] place output answer back into document
- [ ] choice for output format
API Keys (AppID)
<file_sep>const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
lib: './src/lib.js',
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
// output lib.js entry point to functions in variable AppLib
libraryTarget: 'var',
library: 'AppLib',
},
// devtool: 'cheap-source-map',
plugins: [
// clean /dist of any old files
new CleanWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [
{ from: 'appsscript.json' },
{ from: '.clasp.json' },
{ from: 'src/api.js' },
{ from: 'src/sidebar.html' },
]
})
],
}
|
819239db2bfd04ec3d2a7760074ac95a0d02206c
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
jared-hughes/docs-equations-calculator
|
e770763c2c46eef719ea7d70440d5042d1a73c8f
|
e01f33ae3d5ef489a85c63c641ddb7ef5371ca89
|
refs/heads/master
|
<repo_name>eppee/utmaningen<file_sep>/src/main/java/se/per/utmaningen/database/UtmaningenDatabase.java
package se.per.utmaningen.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class UtmaningenDatabase {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
protected static Connection getConnection() {
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", "utmaningen");
connectionProps.put("password", "<PASSWORD>");
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/utmaningen",
connectionProps);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("Kan inte ansluta till databasen.");
}
return conn;
}
}
<file_sep>/src/test/se/per/utmaningen/StockValueFinderTest.java
package se.per.utmaningen;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.ParseException;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.DOMException;
import org.xml.sax.SAXException;
import se.per.utmaningen.finder.TempValue;
public class StockValueFinderTest {
@Test
public void finder() throws MalformedURLException, DOMException, ParserConfigurationException, SAXException, IOException, ParseException {
StockValueFinder finder = new StockValueFinder();
String ticker = "KARO.ST";
TempValue temp1 = finder.findStockPrice(ticker, tickerUrl(ticker, StockValueFinder.TODAYS_VALUES_URL));
TempValue temp2 = finder.findStockPrice(ticker, tickerUrl(ticker, StockValueFinder.TODAYS_VALUES_URL2));
TempValue temp = finder.findLastStockPrice(ticker);
if (temp1.getTime().before(temp2.getTime())) {
Assert.assertEquals(temp2.getTime(), temp.getTime());
} else {
Assert.assertEquals(temp1.getTime(), temp.getTime());
}
}
private String tickerUrl(String ticker, String url) {
return url.replace("TICKER", ticker);
}
}
<file_sep>/src/main/java/se/per/utmaningen/user/ChoiceUser.java
package se.per.utmaningen.user;
import se.per.utmaningen.stock.Stock;
public class ChoiceUser extends User {
private final Stock stock;
public ChoiceUser(int id, String username, Stock choice) {
super(id, username);
this.stock = choice;
}
public ChoiceUser(User user, Stock choice) {
super(user.getId(), user.getUsername());
this.stock = choice;
}
public Stock getStock() {
return stock;
}
}
<file_sep>/src/main/java/se/per/utmaningen/etc/Logger.java
package se.per.utmaningen.etc;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import se.per.utmaningen.database.UtmaningDB;
public class Logger {
public static void log(HttpServletRequest request, String str) {
SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String ip = getClientIpAddress(request);
String header = request.getHeader("User-Agent");
System.out.println("[" + ip + "] [" + header + "] " + sdt.format(new Date()) + " | " + str);
UtmaningDB.log(ip, header);
}
public static void logLoginTry(HttpServletRequest request, String username, String password) {
SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String ip = getClientIpAddress(request);
String info = "Failed to login: " + username + ", password: " + password;
System.err.println("[" + ip + "] [" + info + "] " + sdt.format(new Date()));
UtmaningDB.log(ip, info);
}
private static final String[] HEADERS_TO_TRY = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR" };
public static String getClientIpAddress(HttpServletRequest request) {
for (String header : HEADERS_TO_TRY) {
String ip = request.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr();
}
}
<file_sep>/src/main/java/se/per/utmaningen/database/UtmaningSession.java
package se.per.utmaningen.database;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import se.per.utmaningen.etc.Logger;
import se.per.utmaningen.user.User;
public class UtmaningSession {
private static final String LOGGED_ADMIN = "1<PASSWORD>";
private static final String LOGGED = "als<PASSWORD>";
public static boolean isAdmin(HttpSession session, HttpServletRequest request) {
if (session != null && request != null) {
if (session.getAttribute("logged") != null && session.getAttribute("logged").toString().equals(LOGGED_ADMIN)) {
return true;
}
}
return false;
}
public static boolean isAdminPer(HttpSession session, HttpServletRequest request) {
if (request.getParameter("adminPerLarsson") != null){
session.setAttribute("loggedAdmin", LOGGED_ADMIN);
return true;
}
return false;
}
public static String getMd5(String string) {
try {
String utmaningenExtra = "utmaningenExtra" + string;
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(utmaningenExtra.getBytes());
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Passwordproblem:", e);
}
}
public static boolean login(HttpSession session, HttpServletRequest request) {
String postedUsername = request.getParameter("username");
String postedPassword = request.getParameter("password");
User user;
if (postedUsername != null && postedPassword != null && (user = UtmaningDB.getUser(postedUsername, getMd5(postedPassword))) != null) {
session.setAttribute("logged", user.isAdmin() ? LOGGED_ADMIN : LOGGED);
return true;
} else {
Logger.logLoginTry(request, postedUsername, postedPassword);
}
return false;
}
}
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>se.per.utmaningen</groupId>
<artifactId>Utmaningen</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Utmaningen Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<jettyVersion>9.3.9.v20160517</jettyVersion>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>7.0.82</version>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.yahoofinance-api</groupId>
<artifactId>YahooFinanceAPI</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>Utmaningen</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://192.168.127.12:8080/manager/text</url>
<server>deploymentRepo</server>
<username>deployer</username>
<password><PASSWORD></password>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>/src/main/java/se/per/utmaningen/etc/MathHelper.java
package se.per.utmaningen.etc;
public class MathHelper {
public static double getPercentFromDecimal(double dec) {
return Math.round(dec * 1000) / 10.0;
}
public static double getPercent(double todayClose, double yesterdayClose) {
return MathHelper.getPercentFromDecimal((todayClose - yesterdayClose)/yesterdayClose);
}
}
<file_sep>/src/main/java/se/per/utmaningen/GoogleFinance.java
package se.per.utmaningen;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.net.ssl.SSLHandshakeException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import se.per.utmaningen.finder.TempValue;
import se.per.utmaningen.stock.Stock;
public class GoogleFinance {
public static List<TempValue> getList(String ticker, Date from, Date to) {
List<TempValue> list = new ArrayList<TempValue>();
String json = getJsonFromUrl("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=" + ticker + "&apikey=<KEY>");
ObjectMapper mapper = new ObjectMapper();
Alpha jackson;
SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(from);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
try {
jackson = mapper.readValue(json, Alpha.class);
if (jackson.getTimeSeries() != null && jackson.getTimeSeries().getProperties() != null) {
for (String key : jackson.getTimeSeries().getProperties().keySet()) {
if (sdt.parse(key).compareTo(cal.getTime()) >= 0) {
DatePrice datePrice = jackson.getTimeSeries().getProperties().get(key);
TempValue temp = new TempValue(key, new Float(datePrice.getOpen()), new Float(datePrice.getClose()), ticker);
list.add(temp);
}
}
}
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
private static String getJsonFromUrl(String string) {
String json = "";
try {
URL url = new URL(string);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
json += inputLine;
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SSLHandshakeException e) {
System.out.println("SSLHandshakeException in getJsonFromUrl:81");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
public static Stockinfo getStockInfo(String ticker) {
String json = getJsonFromUrl("https://finance.google.com/finance?output=json&q=" + ticker);
if (!json.startsWith("{")) {
json = json.substring(4, json.length() - 1);
}
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(json, Stockinfo.class);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static TempValue getIntradayLastPrice(Stock stock) throws JsonMappingException, IOException {
//String json = getJsonFromUrl("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=" + stock.getTicker() + "&interval=1min&outputsize=compact&apikey=<KEY>");
String json = getJsonFromUrl("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=" + stock.getTicker() + "&apikey=<KEY>");
ObjectMapper mapper = new ObjectMapper();
Alpha jackson;
try {
jackson = mapper.readValue(json, Alpha.class);
if (jackson.getTimeSeries() != null && jackson.getTimeSeries().getProperties() != null) {
System.out.println("Found minutes!");
String lastMinute = null;
for (String key : jackson.getTimeSeries().getProperties().keySet()) {
if (lastMinute == null || lastMinute.compareTo(key) < 0) {
lastMinute = key;
}
}
if (lastMinute != null) {
DatePrice minute = jackson.getTimeSeries().getProperties().get(lastMinute);
TempValue temp = new TempValue(lastMinute.substring(0, 10), new Float(minute.getOpen()), new Float(minute.getClose()), stock.getName());
return temp;
}
}
} catch (JsonParseException e) {
System.err.println("Not good: " + e.getMessage());
e.printStackTrace();
} catch (ParseException e) {
System.err.println("Not good: " + e.getMessage());
e.printStackTrace();
}
return null;
}
}
<file_sep>/src/main/java/se/per/utmaningen/Stockinfo.java
package se.per.utmaningen;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Stockinfo {
private String name;
public Stockinfo() {
super();
}
@JsonGetter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
1f02564d5c96ef85224eb9a59d9c2e67dd2b72e8
|
[
"Java",
"Maven POM"
] | 9
|
Java
|
eppee/utmaningen
|
2d0af3b815a78957ba9c5a746a1c9343e5b47398
|
9d29e68347abe6c0038f7b5c568d59fdf29b0994
|
refs/heads/master
|
<repo_name>jaredmoskowitz/comp20-jmoskowitz<file_sep>/messages/README.txt
README.txt
Lab: Messages, Part 2
COMP 20
<NAME>
1. To my knowledge everything has been correctly implemented.
2. N/A
3. 1 hour
Part 2: Loading the Data From Local Machine:
Opening the file in a browser worked for Firefox, but not Chrome or Safari. Chrome
and Safari threw the error "Cross origin requests are only supported for HTTP."
See later answer for why it shouldn't work.
Part 3: Loading the Data Given a URI
Requesting the json from the given URI does not work. Firefox and Chrome returned the
error: "No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8000' is therefore not allowed access."
Is it possible to request the data from a different origin
(e.g., http://messagehub.herokuapp.com/) or from your local machine (from file:///)
from using XMLHttpRequest? Why or why not?
It is not possible unless a CORS is used. The reason the URI example doesn't work is
because of the same-origin policy. A request is being made to a different host
than the local host the request is being executed on. The local machine doesn't
work because part of the same-origin policy is that the requests must be executed
on a server. One reason why a browser would not allow accessing local files, even
if they are in the same directory, is because a web page could access a user's
hard drive this way.
<file_sep>/mbta/main.js
var map;
var userLocation;
userToClosestStopLineColor = '#3F133D';
redLineColor = '#FF0000';
markerIconPath = 'marker.png'
SouthStation = {name: "South Station", coords: {lat: 42.352271, lng: -71.05524200000001}};
Andrew = {name: "Andrew", coords: {lat: 42.330154, lng: -71.057655}};
PorterSquare = {name: "Porter Square", coords: {lat: 42.3884, lng: -71.11914899999999}};
HarvardSquare = {name: "Harvard Square", coords: {lat: 42.373362, lng: -71.118956}};
JFKUMass = {name: "JKF/UMass", coords: {lat: 42.320685, lng: -71.052391}};
SavinHill = {name: "<NAME>", coords: {lat: 42.31129, lng: -71.053331}};
ParkStreet = {name: "Park Street", coords: {lat: 42.35639457, lng: -71.0624242}};
Broadway = {name: "Broadway", coords: {lat: 42.342622, lng: -71.056967}};
NorthQuincy = {name: "North Quincy", coords: {lat: 42.275275, lng: -71.029583}};
Shawmut = {name: "Shawmut", coords: {lat: 42.29312583, lng: -71.06573796000001}};
Davis = {name: "Davis", coords: {lat: 42.39674, lng: -71.121815}};
Alewife = {name: "Alewife", coords: {lat: 42.395428, lng: -71.142483}};
KendallMIT = {name: "Kendall/MIT", coords: {lat: 42.36249079, lng: -71.08617653}};
CharlesMGH = {name: "Charles/MGH", coords: {lat: 42.361166, lng: -71.070628}};
DowntownCrossing= {name: "<NAME>", coords: {lat: 42.355518, lng: -71.060225}};
QuincyCenter = {name: "<NAME>", coords: {lat: 42.251809, lng: -71.005409}};
QuincyAdams = {name: "<NAME>", coords: {lat: 42.233391, lng: -71.007153}};
Ashmont = {name: "Ashmont", coords: {lat: 42.284652, lng: -71.06448899999999}};
Wollaston = {name: "Wollaston", coords: {lat: 42.2665139, lng: -71.0203369}};
FieldsCorner = {name: "Fields Corner", coords: {lat: 42.300093, lng: -71.061667}};
CentralSquare = {name: "Central Square", coords: {lat: 42.365486, lng: -71.103802}};
Braintree = {name: "Braintree", coords: {lat: 42.2078543, lng: -71.0011385}};
var redStops = [SouthStation,
Andrew,
PorterSquare,
HarvardSquare,
JFKUMass,
SavinHill,
ParkStreet,
Broadway,
NorthQuincy,
Shawmut,
Davis,
Alewife,
KendallMIT,
CharlesMGH,
DowntownCrossing,
QuincyCenter,
QuincyAdams,
Ashmont,
Wollaston,
FieldsCorner,
CentralSquare,
Braintree];
var redRoute = [[Alewife, [Davis]],
[Davis, [PorterSquare]],
[PorterSquare, [HarvardSquare]],
[HarvardSquare, [CentralSquare]],
[CentralSquare, [KendallMIT]],
[KendallMIT, [CharlesMGH]],
[CharlesMGH, [ParkStreet]],
[ParkStreet, [DowntownCrossing]],
[DowntownCrossing, [SouthStation]],
[SouthStation, [Broadway]],
[Broadway, [Andrew]],
[Andrew, [JFKUMass]],
[JFKUMass, [NorthQuincy, SavinHill]],
[NorthQuincy, [Wollaston]],
[Wollaston, [QuincyCenter]],
[QuincyCenter, [QuincyAdams]],
[QuincyAdams, [Braintree]],
[SavinHill, [FieldsCorner]],
[FieldsCorner, [Shawmut]],
[Shawmut, [Ashmont]]];
function init() {
initMap();
}
/* initialize map to have markers and polylines */
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: SouthStation.coords,
zoom: 3
});
//set up MBTA
markers = placeMarkers(map, redStops, markerIconPath);
for (var i = 0; i < redStops.length; i++) {
(function (name) {
markers[i].addListener('click', function () {
setStopInfoWindow(name, this, map);
});
})(redStops[i].name);
}
drawRoute(map, redRoute, redLineColor);
//user location specific things
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setupUserLocation);
} else {
console.log("Geolocation is not supported by this browser");
}
}
/* places markers on map for given array of stops */
function placeMarkers(map, stops, iconPath) {
markers = [];
for (var i = 0; i < stops.length; i++) {
markers.push(placeMarker(map, stops[i].coords, stops[i].name, iconPath));
}
return markers;
}
/* places a marker on given map */
function placeMarker(map, coords, name, iconPath) {
var marker = new google.maps.Marker({
position: coords,
map: map,
title: name,
icon: iconPath
});
return marker;
}
function addClickHandlerToMarker(marker, map, callback) {
}
/* draws route on map for given (directional) adjacency list of stops */
function drawRoute(map, route, color) {
for (var i = 0; i < route.length; i++) {
stop = route[i][0];
var edge = [];
edge.push(stop.coords);
/* loop to handle forks */
for (var j = 0; j < route[i][1].length; j++) {
edge.push(route[i][1][j].coords)
var path = new google.maps.Polyline({
path: edge,
geodesic: true,
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 2
});
path.setMap(map);
edge.pop();
}
}
}
/* sets marker, info window, and polyine to closest stop */
function setupUserLocation(position) {
userLoc = {name: "<NAME>", coords: {lat: position.coords.latitude, lng: position.coords.longitude}};
locDistances = getClosestLocationsFromPoint(userLoc.coords, redStops);
var marker = placeMarker(map, userLoc.coords, userLoc.name, null);
setUserInfoWindow(marker, userLoc.coords, locDistances, map);
//draw line to closest station
drawRoute(map, [[userLoc, [locDistances[0].location]]], userToClosestStopLineColor);
}
/* Sets the html for when the user marker is clicked */
function setUserInfoWindow(userMarker, coords, locDistances, map) {
var contentString = '<div id="content">'+
'<div>'+
'<p>Stop closest to you: ' +
locDistances[0].location.name +
'</p>' +
'<p>' +
getUserInfoTableString(locDistances) +
'</p>' +
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
userMarker.addListener('click', function() {
infowindow.open(map, userMarker);
});
}
/* returns a string representing the html for the info window on the user marker*/
function getUserInfoTableString(locDistances) {
entriesString = '';
for(var i = 0; i<locDistances.length; i++) {
entriesString += '' +
'<tr>' +
'<td>' + locDistances[i].locationName + '</td>' +
'<td>' + locDistances[i].distance + '</td>' +
'</tr>';
}
htmlTable = '' +
'<table id=\"table1\">' +
'<tr>' +
'<th>Name</th>' +
'<th>Distance (mi)</th>' +
'</tr>' +
entriesString +
'</table>';
return htmlTable;
}
/* Sets the html for when a stop is clicked */
function displayStopInfoWindow(predictions, marker, map) {
var titleString;
if (predictions.length <= 0) {
titleString = "Sorry, no trains are coming!";
} else {
titleString = predictions[0].stop;
}
var contentString = '<div id="content">'+
'<div>'+
'<p>' +
titleString +
'</p>' +
'<p>' +
getStopInfoTableString(predictions) +
'</p>' +
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
infowindow.open(map, marker);
}
function getStopInfoTableString(predictions) {
entriesString = '';
for(var i = 0; i < predictions.length; i++) {
entriesString += '' +
'<tr>' +
'<td>' + predictions[i].destination + '</td>' +
'<td>' + predictions[i].seconds + '</td>' +
'</tr>';
}
htmlTable = '' +
'<table id=\"table2\">' +
'<tr>' +
'<th>Destination</th>' +
'<th>Seconds</th>' +
'</tr>' +
entriesString +
'</table>';
return htmlTable;
}
/*
returns an array in ascending order of distance from given point
where each element has format: {locationName: __, distance:__ }
*/
function getClosestLocationsFromPoint(point, locations) {
var arr = [];
for (var i = 0; i < locations.length; i++) {
arr.push({
location: locations[i],
distance: distanceBetweenCoords(point, locations[i].coords)
});
}
return arr.sort(function(a, b){return a.distance-b.distance});
}
/* calculates the distance between two coordinates */
function distanceBetweenCoords(coord1, coord2) {
var lat2 = coord2.lat;
var lon2 = coord2.lng;
var lat1 = coord1.lat;
var lon1 = coord1.lng;
// The below implementation for getting the distance between two geocoords
// was found at the following URL:
// http://stackoverflow.com/questions/14560999/using-the-haversine-formula-in-javascript
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
var R = 3956.55; // miles
//has a problem with the .toRad() method below.
var x1 = lat2-lat1;
var dLat = x1.toRad();
var x2 = lon2-lon1;
var dLon = x2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
function setStopInfoWindow(stopName, marker, map) {
var request = new XMLHttpRequest();
request.open("GET", "https://whispering-wildwood-58478.herokuapp.com/redline.json", true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
jsondata = request.responseText;
console.log(jsondata);
predictions = parseTrips(jsondata, stopName);
displayStopInfoWindow(predictions, marker, map);
}
else if (request.readyState == 4 && request.status != 200) {
console.log("Something went wrong with the request!");
}
else
{
console.log("In progress...");
}
};
request.send(null);
}
function parseTrips(jsondata, stopName) {
data = JSON.parse(jsondata);
trips = data.TripList.Trips;
stopSchedule = [];
for (var i = 0; i < trips.length; i++) {
trip = trips[i];
dest = trip.Destination;
console.log("stop: " + stopName);
for (var j = 0; j < trip.Predictions.length; j++) {
if (trip.Predictions[j].Stop == stopName) {
stopSchedule.push({
stop: stopName,
destination: dest,
seconds: trip.Predictions[j].Seconds
});
}
}
}
return stopSchedule;
}
<file_sep>/messages/lab.js
var request = new XMLHttpRequest();
function parse() {
request.open("GET", "data.json", true);
request.onreadystatechange = function() {
console.log("readyState: " + request.readyState);
if (request.readyState == 4 && request.status == 200) {
console.log("Got the data back");
jsondata = request.responseText;
console.log(jsondata);
messages = JSON.parse(jsondata);
var messagesDiv = document.getElementById('messages');
for (var i = 0; i < messages.length; i++) {
object = messages[i];
id = object['id'];
content = object['content'];
username = object['username'];
var para = document.createElement("p");
para.id = "p" + id.toString();
var node = document.createTextNode(content + " " + username);
para.appendChild(node);
messagesDiv.appendChild(para);
}
}
else if (request.readyState == 4 && request.status != 200) {
document.getElementById('messages').innerHTML = "<p> Whoops, something went wrong </p>";
}
else
{
console.log("In progress...");
}
};
request.send(null);
}
<file_sep>/mbta/README.txt
README.txt
COMP 20 Lab: Closest MBTA Subway Station Part 2
<NAME>
1. I believe everything has been implemented correctly. In addition, the user
info window displays a table of distances from user to all stops.
2. N/A
3. 5.5 hours
<file_sep>/security/spam.sh
#!/bin/bash
for (( j = 0; j < 10000; j++ ));
do
LA=$((i % 180))
LN=$((j % 180))
ENTRY="login=spamking&lat=$LA&lng=$LN"
echo $DATA
curl --data $ENTRY https://powerful-tor-64243.herokuapp.com/sendLocation
done
<file_sep>/responsive/README.txt
1. It starts at top right on comic when smallest and expanding goes further in the comic but it should
be starting when screen largest.
2. I did not discuss/collaborate with anyone
3. An hour and a half
<file_sep>/my_old_kentucky_home/README.txt
COMP 20 Lab: My Old Kentucky Home
<NAME>
1. To my knowledge, everything has been implemented correctly.
2. N/A
3. 3 hours
<file_sep>/security/README.txt
Assignment 4: Security and Privacy Assessment of a Web Application
<NAME>
1. Everything to my knowledge has been implemented correctly.
2. <NAME>
3. 6 hours
|
10a9166d76c7926f345c4b8497160e84de4168c4
|
[
"JavaScript",
"Text",
"Shell"
] | 8
|
Text
|
jaredmoskowitz/comp20-jmoskowitz
|
53e93c6765996d72f184c6b6dcef680652dd7703
|
2563d115f655a784f7cad0578f3956a347249fef
|
refs/heads/master
|
<repo_name>alcarv/calculadora<file_sep>/README.md
# calculadora
calc project em php
<file_sep>/index.php
<?php
print_r("Hello Word");
?>
|
3b2f058cab248e8350d2374836194c2c54ca8fd1
|
[
"Markdown",
"PHP"
] | 2
|
Markdown
|
alcarv/calculadora
|
e7216c38e031cbf904a47f2bb2e2fe57d4add972
|
1bf6a83db2a9f6f7aab287de9c9187730308d16b
|
refs/heads/master
|
<repo_name>cthielen/sympa-sync<file_sep>/models/person.rb
require 'active_resource'
class Person < ActiveResource::Base
begin
rm_settings = YAML.load_file("config/dss-rm.yml")['dssrm']
self.site = rm_settings["endpoint"]
self.user = rm_settings["username"]
self.password = rm_settings["password"]
rescue Errno::ENOENT => e
puts "config/dss-rm.yml is missing. Please fix (see config/dss-rm.example.yml)."
end
# Required by declarative_authorization to determine access
def role_symbols
roles.map { |x| x.to_sym }
end
# Returns true if the given symbol is in this.role_symbols
def has_role?(role_sym)
role_symbols.include? role_sym
end
end
<file_sep>/README.md
Sympa Sync
==========
Sympa Sync is a working example of the DSS-RM API (see http://github.com/cthielen/dss-rm), serving to synchronize data between DSS-RM and a Sympa-based mailing list server. It employes the Sympa SOAP API to do so.
<file_sep>/sympa-sync.rb
load 'models/application.rb'
load 'models/person.rb'
require 'pp'
# Fake Sympa lists (to be replaced with Sympa API calls later)
sympa_lists = {'history-staff' => {:touched => false}, 'history-fac' => {:touched => false}, 'dssit-devs' => {:touched => false}, 'econ-all' => {:touched => false}}
# Get a list of all applications
applications = Application.all
puts "Existing applications:"
# Go through each application and sync with the lists
applications.each do |application|
puts application.name
if sympa_lists.include? application.name
puts "\tfound in list"
else
puts "\tnot found in list"
end
end
puts "New lists:"
# Check to see if any lists weren't synced (new lists)
sympa_lists.reject{|key,value| value[:touched] == true }.each do |new_list|
puts "\t#{new_list}"
end
<file_sep>/models/application.rb
require 'active_resource'
class Application < ActiveResource::Base
begin
rm_settings = YAML.load_file("config/dss-rm.yml")['dssrm']
self.site = rm_settings["endpoint"]
self.user = rm_settings["username"]
self.password = rm_settings["password"]
rescue Errno::ENOENT => e
puts "config/dss-rm.yml is missing. Please fix (see config/dss-rm.example.yml)."
end
end
|
ef9fae69c0b0c5435735570afd5474dc9c39be6e
|
[
"Markdown",
"Ruby"
] | 4
|
Ruby
|
cthielen/sympa-sync
|
338da5dd2b69b1d3cdef4358886bc6b75235c96d
|
aaccc6ae86a7cb5346dffb7fd12d5397942c95b8
|
refs/heads/master
|
<file_sep># INTERNAL TESTING
### Installation
- Ensure you have the latest version of npm and NodeJS LTS version (8.11.1) or higher.
- Also make sure MongoDB is installed.
- Download or clone a git repository:
```
https://github.com/shpp-alyabihova/internal-testing.git
```
- Import collection from assert folder:
```
mongoimport --db DB_NAME --collection weather --file parsed_weather.json
```
```
mongoimport --db DB_NAME --collection school --file parsed_school.json
```
- Configure `config.json` file from `config` folder
- From the project folder, execute the following command to install project dependencies:
```
npm install
```
- For run test start the `index_test.js`:
```
node index_test.js
```
The script returns the object with names of tasks and its results.
- For execution task #2 separately in mongo console run script `quert2.js` from `scripts` folder.
```
mongo DB_NAME query2.js
```
Before executing the script - make sure that the collection is initialized with the source `parsed_weather.json` file.
- For execution task #3 separately in mongo console run script `quert3.js` from `scripts` folder.
```
mongo DB_NAME query3.js
```
Before executing the script - make sure that the collection is initialized with the source `parsed_school.json` file
and has not undergone any changes.<file_sep>const mongodb = require('mongodb');
const util = require('util');
const config = require('config');
const mongoClient = util.promisify(mongodb.MongoClient);
const DATABASE_URI = config.get('db.uri');
const OPTIONS = config.get('db.options');
module.exports.connect = (uri = DATABASE_URI, options = OPTIONS) => mongoClient
.connect(uri, options)
.catch(error => console.error(error));
module.exports.closeConnect = (client) => client.close();
<file_sep>const object = require('lodash/object');
const { connect, closeConnect } = require('./mongodb');
const config = require('config');
const DB_NAME = config.get('db.name');
const COLLECTION = config.get('weather.collectionName');
const WIND_DIRECTION = config.get('weather.windDirection');
module.exports.getStateWithMinTemperature = async (windDirection = WIND_DIRECTION) => {
const client = await connect();
const db = client.db(DB_NAME);
const selection = await db.collection(COLLECTION).aggregate([ {
$match: {
windDirection: {
$gte: object.get(windDirection, 'min'),
$lte: object.get(windDirection, 'max')
}
}
}, {
$group: {
_id: '$state',
temp: {
$min: '$temperature'
}
}
}]).toArray();
await closeConnect(client);
return object.get(selection, '[0]._id');
};
//.find({ windDirection: { $gte: object.get(windDirection, 'min'), $lte: object.get(windDirection, 'max') } }).sort({ temperature: 1 }).limit(1).toArray();<file_sep>cursor = db.school.aggregate([
{ $unwind: '$scores' },
{ $match: { 'scores.type': 'homework' }},
{ $group: { _id: '$_id', minscore: { $min: '$scores.score' } } }
]);
cursor.forEach(function (coll) {
db.school.update({
_id: coll._id,
}, {
$pull: {
'scores': {
type: 'homework',
score: coll.minscore
}
}
});
});
agrigation = db.school.aggregate([
{ $unwind: '$scores' },
{ $group: { _id: '$_id', avgscore: { $avg: '$scores.score' } } },
{ $sort: { avgscore: -1 } },
{ $limit: 1 }
]).toArray();
print(agrigation[0]['_id']);
<file_sep>const db = require('../db/weather');
module.exports.getStateWithMinTemperature = async () => {
try {
return await db.getStateWithMinTemperature();
} catch (error) {
console.error(error);
}
};<file_sep>agrigation = db.weather.aggregate([ {
$match: {
windDirection: {
$gte: 180,
$lte: 360
}
}
}, {
$group: {
_id: '$state',
temp: {
$min: '$temperature'
}
}
}]).toArray();
print(agrigation[0]['_id']);<file_sep>const object = require('lodash/object');
const { connect, closeConnect } = require('./mongodb');
const config = require('config');
const DB_NAME = config.get('db.name');
const COLLECTION = config.get('school.collectionName');
module.exports.updateSchoolScore = async () => {
const client = await connect();
const db = client.db(DB_NAME);
const cursor = await db.collection(COLLECTION).aggregate([
{ $unwind: '$scores' },
{ $match: { 'scores.type': 'homework' } },
{ $group: { _id: '$_id', minscore: { $min: '$scores.score' } } }
]).toArray();
for (let coll of cursor) {
await db.collection(COLLECTION).update({
_id: coll._id,
}, {
$pull: {
'scores': {
type: 'homework',
score: coll.minscore
}
}
});
}
await closeConnect(client);
};
module.exports.getSuccessfulStudent = async () => {
const client = await connect();
const db = client.db(DB_NAME);
const student = await db.collection(COLLECTION).aggregate([
{ $unwind: '$scores' },
{ $group: { _id: '$_id', avgscore: { $avg: '$scores.score' } } },
{ $sort: { avgscore: -1 } },
{ $limit: 2 }
]).toArray();
await closeConnect(client);
return object.get(student, '[0]._id');
};<file_sep>const array = require('lodash/array');
const object = require('lodash/object');
const sharp = require('sharp');
const util = require('util');
const fs = require('fs');
const config = require('config');
const asyncFs = ['writeFile', 'readFile', 'stat', 'mkdir', 'readdir']
.reduce((obj, funcName) => (object.set(obj, funcName, util.promisify(fs[funcName]))), {});
const FILE_PATH = config.get('images.path');
const OUTPUT_DIR = config.get('images.outputDir');
const SIZES = config.get('images.sizes');
module.exports.resizeImages = async (filePath = FILE_PATH) => {
const filesList = await getFiles(filePath);
const imageList = array.flattenDeep(filesList).filter(fileName => fileName.toLowerCase().endsWith('.jpg'));
await ensureDir(OUTPUT_DIR);
await Promise.all(imageList.map(image => resizeImageToMultipleSize(image)));
};
async function ensureDir(dirPath) {
try {
await asyncFs.stat(dirPath);
} catch (error) {
if (object.get(error, 'code') === 'ENOENT') {
await createDirTree(dirPath);
}
}
}
async function createDirTree(dirPath) {
const dirNodes = dirPath.split('/').filter(node => !node.startsWith('.'));
return dirNodes.reduce(async (prevPromise, node) => {
const path = await prevPromise;
await asyncFs.mkdir(`${path}/${node}`).catch(error => console.error(error));
return Promise.resolve(`${path}/${node}`);
}, Promise.resolve('.'));
}
async function resizeImageToMultipleSize(image) {
const fileBuff = await asyncFs.readFile(image);
await Promise.all(SIZES.map(async size => {
try {
const resizedImage = await resize(fileBuff, size);
await asyncFs.writeFile(`${OUTPUT_DIR}/${size}x${size}_${array.last(image.split('/'))}`, resizedImage);
} catch (error) {
console.error(error);
}
}));
}
async function resize(buff, size) {
return sharp(buff)
.resize(size, size)
.withoutEnlargement(true)
.toBuffer();
}
async function getFiles(sourcePath) {
const stats = await asyncFs.stat(sourcePath);
if (stats.isFile()) {
return array.concat(sourcePath);
} else if (stats.isDirectory()){
return getFileList(sourcePath);
}
return [];
}
async function getFileList(dirPath) {
const fileList = await asyncFs.readdir(dirPath);
return await Promise.all(fileList.map(filePath => getFiles(`${dirPath}/${filePath}`)));
}
<file_sep>const config = require('config');
const object = require('lodash/object');
const school = require('./modules/school');
const weather = require('./modules/weather');
const resizer = require('./modules/image-resizer');
const OUTPUT_DIR = config.get('images.outputDir');
const IMAGE_RESIZE_TEST_NAME = config.get('images.testName');
const WEATHER_TEST_NAME = config.get('weather.testName');
const SCHOOL_TEST_NAME = config.get('school.testName');
async function init() {
const result = {};
await resizer.resizeImages();
object.set(result, IMAGE_RESIZE_TEST_NAME, OUTPUT_DIR);
object.set(result, WEATHER_TEST_NAME, await weather.getStateWithMinTemperature());
await school.updateSchoolScore();
object.set(result, SCHOOL_TEST_NAME, await school.getSuccessfulStudent());
return { result };
}
init()
.then(result => console.log(result))
.catch(error => console.error(error));
|
48824ae3df9f3be8bad608ee83e92257283be000
|
[
"Markdown",
"JavaScript"
] | 9
|
Markdown
|
shpp-alyabihova/internal-testing
|
09a2eb35f2b66e9dfafcaa75a69c728c843c4fdc
|
b08e282e0d331fd7045a2cbf4087e6bc0291f0b8
|
refs/heads/master
|
<repo_name>xgbuils/ca-juggol<file_sep>/Gruntfile.js
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-jshint')
// commonjs to module for browser
grunt.loadNpmTasks('grunt-browserify')
grunt.loadNpmTasks('grunt-focus')
grunt.loadNpmTasks('grunt-contrib-copy')
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-contrib-connect')
grunt.loadNpmTasks('grunt-contrib-watch')
grunt.loadNpmTasks('grunt-contrib-stylus')
grunt.loadNpmTasks('grunt-contrib-concat')
grunt.loadNpmTasks('grunt-template');
var ENV = ['prod', 'dev']
var LANG = ['ca', 'es', 'en']
var browserify = {}
var connect = {}
var copy = {
'fonts-dev-ca': {
expand: true,
cwd: 'src/fonts',
src: ['**/*'],
dest: 'dist/dev/ca/fonts',
},
'fonts-prod-ca': {
expand: true,
cwd: 'src/fonts/',
src: ['**/*'],
dest: 'dist/prod/ca/fonts/',
},
}
var focus = {}
var stylus = {
options: {
use: [
require('nib')
]
}
}
var template = {}
var uglify = {}
var watch = {
options: {
livereload: true
}
}
ENV.forEach(function (env) {
LANG.forEach(function (lang) {
// browserify
browserify[env + '-' + lang] = {
src: 'src/js/main.js',
dest: 'dist/' + env + '/' + lang + '/js/main.js'
}
// focus
focus[env + '-' + lang] = {
include: [
'watch:scripts-' + env + '-' + lang,
'watch:template-' + env + '-' + lang,
'watch:stylus-' + env + '-' + lang
]
}
// connect
connect[env + '-' + lang] = {
options: {
port: env === 'dev' ? 9090 : 9099,
hostname: 'localhost',
base: 'dist/' + env + '/' + lang,
livereload: true
}
}
// copy jquery
copy['jquery-' + env + '-' + lang] = {
expand: true,
cwd: 'bower_components/jquery/dist/',
src: ['jquery.min.js'],
dest: 'dist/' + env + '/' + lang + '/js/',
}
// copy fonts
copy['fonts-' + env + '-' + lang] = {
expand: true,
cwd: 'src/fonts',
src: ['**/*'],
dest: 'dist/' + env + '/' + lang + '/fonts'
}
// stylus
stylus[env + '-' + lang] = {
options: {
linenos: false,
compress: env === 'prod'
},
files: [{
expand: true,
cwd: 'src/styles/',
src: [ 'main.styl' ],
dest: 'dist/' + env + '/' + lang + '/styles/',
ext: '.css'
}]
}
// template
var files = {}
files['dist/' + env + '/' + lang + '/index.html'] = ['src/index.html.tpl']
template[env + '-' + lang] = {
options: {
data: require('./src/lang/' + lang + '.js')
},
files: files
}
var scriptTasks = ['browserify:' + env + '/' + lang]
if (env === 'prod') {
scriptTasks.push('uglify:prod-' + lang)
}
watch['scripts-' + env + '-' + lang] = {
files: ['src/js/main.js', 'src/js/Juggler/**/*.js'],
tasks: ['browserify:' + env + '-' + lang]
}
watch['stylus-' + env + '-' + lang] = {
files: ['src/**/*.styl'],
tasks: ['stylus:' + env + '-' + lang]
}
watch['template-' + env + '-' + lang] = {
files: ['src/index.html.tpl', 'src/lang/*.js'],
tasks: ['template:' + env + '-' + lang]
}
})
})
LANG.forEach(function (lang) {
var files = {}
files['dist/prod/' + lang + '/js/main.js'] = ['dist/prod/' + lang + '/js/main.js']
uglify['prod-' + lang] = {
files: files
}
})
var config = {
browserify: browserify,
connect: connect,
copy: copy,
focus: focus,
stylus: stylus,
template: template,
uglify: uglify,
watch: watch,
}
grunt.initConfig(config);
ENV.forEach(function (env) {
LANG.forEach(function (lang) {
var sufix = env + '-' + lang
grunt.registerTask('copy:' + sufix, [
'template:' + sufix,
'copy:fonts-' + sufix,
'copy:jquery-' + sufix
])
var buildTasks = [
'copy:' + sufix,
'stylus:' + sufix,
'browserify:' + sufix
]
if (env === 'prod') {
buildTasks.push('uglify:prod-' + lang)
}
grunt.registerTask('build:' + sufix, buildTasks)
grunt.registerTask('server:' + sufix, [
'build:' + sufix,
'connect:' + sufix,
'switchwatch:scripts-' + sufix + ':' + 'template-' + sufix + ':' + 'stylus-' + sufix
]);
/*
grunt.registerTask('watch:' + env + '-' + lang, [
'concurrent:watch-' + env + '-' + lang,
])*/
})
})
grunt.registerTask('switchwatch', function() {
var targets = Array.prototype.slice.call(arguments, 0);
Object.keys(grunt.config('watch')).filter(function(target) {
return !(grunt.util._.indexOf(targets, target) !== -1);
}).forEach(function(target) {
grunt.log.writeln('Ignoring ' + target + '...');
grunt.config(['watch', target], {files: []});
});
grunt.task.run('watch');
});
};<file_sep>/src/js/main.js
var siteswapGenerator = require('siteswap-generator')
var Juggler = require('./Juggler/juggler.js')
var lang = require('language')
var ua = window.navigator.userAgent
var native_android_browser = /android/i.test(ua) && ua.indexOf('534.30')
function ErrorHandler() {
this._length = 0
this._errors = {}
}
ErrorHandler.prototype = {
ok: function () {
return this._length === 0
},
add: function (type, message) {
if (!(type in this._errors)) {
++this._length
}
this._errors[type] = message
},
remove: function (type) {
if (type in this._errors) {
delete this._errors[type]
--this._length
}
},
message: function () {
for (var key in this._errors) {
return this._errors[key]
}
}
}
$.fn.keyboard = function (sequence, callback) {
callback = callback || function (e) {return e}
$(this).html('<ul>'
+ sequence.map(function (e) {
return '<li>' + callback(e) + '</li>'
}).join('')
+ '</ul>')
}
function range(min, max) {
var arr = []
for (var i = min; i <= max; ++i) {
arr.push(i)
}
return arr
}
function triggerDelegatedEvent (name, $wrapper, elem) {
var e = $.Event(name)
e.target = elem
$wrapper.trigger(e)
}
function parseHref(href, config) {
//console.log(href)
var aux = href.split('?')
var fragment = aux[0]
var queryString = {}
//console.log(aux[1])
if (aux[1]) {
var q = aux[1].split('&')
for (var i in q) {
aux = q[i].split('=')
queryString[aux[0]] = aux[1]
}
}
return {
fragment: fragment || config.fragment,
queryString: queryString
}
}
function isInt(value) {
return !isNaN(value) && value === Math.floor(value)
}
function validate (values, type, minmax, option) {
var message = lang.message
var range = values[type]
var value = range[minmax]
if (!isInt(value)) {
errorHandler.add(minmax + type, message.isNotAInt(value))
} else {
errorHandler.remove(minmax + type)
}
if (option === 'all' || option === 'range') {
if(range.min > range.max) {
console.log('min > max')
errorHandler.add(type, message.invalidRange(range, type))
console.log(errorHandler.ok())
} else {
errorHandler.remove(type)
}
}
if (option === 'all') {
var minBalls = values.balls.min
var maxHeights = values.heights.max
var minPeriods = values.periods.min
if (maxHeights <= minBalls && minPeriods > 1) {
errorHandler.add('all', message.emptyWithBigPeriod())
} else if(minPeriods === 1 && maxHeights < minBalls) {
errorHandler.add('all', message.emptyWithLittlePeriod())
} else {
errorHandler.remove('all')
}
}
}
var generateText = {
balls: function (text, balls, $output) {
text.error = false
if (balls.min !== undefined && balls.max !== undefined
&& balls.min <= balls.max && balls.min > 0) {
if (balls.min === balls.max)
text.balls = lang.balls[0](balls.min, balls.max)
else if (balls.min === 1)
text.balls = lang.balls[1](balls.min, balls.max)
else if (balls.min < balls.max)
text.balls = lang.balls[2](balls.min, balls.max)
} else {
text.error = lang.balls[3](balls.min, balls.max)
}
$output.text(text.balls)
},
periods: function (text, period, $output) {
text.error = false
//console.log(period)
if (period.min !== undefined && period.max !== undefined
&& period.min <= period.max && period.min > 0) {
if (period.min === period.max)
text.period = lang.periods[0](period.min, period.max)
else if (period.min === 1)
text.period = lang.periods[1](period.min, period.max)
else if (period.min < period.max)
text.period = lang.periods[2](period.min, period.max)
} else {
text.error = lang.periods[3](period.min, period.max)
}
$output.text(text.period)
},
heights: function (text, height, $output) {
text.error = false
if (height.min === undefined && height.max === undefined) {
text.height = ''
} else if ((height.min === undefined || height.min <= 1) && height.max >= 0) {
text.height = lang.heights[0](height.min, height.max)
} else if (height.max === undefined && height.min >= 0) {
text.height = lang.heights[1](height.min, height.max)
} else if (height.min <= height.max && height.min >= 0) {
if (height.min === height.max) {
text.height = lang.heights[2](height.min, height.max)
} else {
text.height = lang.heights[3](height.min, height.max)
}
} else {
text.error = lang.heights[4](height.min, height.max)
}
$output.text(text.height)
}
}
var text = {}
var values = {}
var errorHandler = new ErrorHandler()
var heightToLetter = "0123456789abcdefghijklmnopqrstuvxyz"
var scope = {
values: {},
href: {
queryString: {}
}
}
$(document).ready(function (event) {
scope.$root = $('body, html')
var DELAY = 300
$('.collapsed').each(function (index, item) {
var $item = $(item)
$item.removeClass('hide')
var width = $item.outerWidth()
console.log(width)
$item.data('width', width)
$item.css('width', width)
//$item.addClass('hide')
})
$('.word-expanded').each(function (index, item) {
var $item = $(item)
var width = $item.outerWidth()
$item.data('width', width)
$item.css('width', width)
})
var $keyboard = scope.$keyboard = $('#keyboard')
var buttons = {}
$keyboard.data('$shown', null)
$.each(['balls', 'periods', 'heights', 'patterns'], function (index, item) {
var $item = buttons['$' + item] = $('#keyboard-' + item)
$item.data('position', 0)
$item.data('active', false)
})
$keyboard.data('buttons', buttons)
var $left = $('#keyboard-left' )
var $right = $('#keyboard-right')
$keyboard.data('$left', $left )
$keyboard.data('$right', $right)
scope.outputs = {
balls: $('#description-balls'),
periods: $('#description-periods'),
heights: $('#description-heights'),
}
scope.message = {
$success: $('#success'),
$error: $('#error')
}
var $wrapper = scope.$wrapper = $('#wrapper')
scope.$create = $('#create')
scope.topCreate = scope.$create.offset().top
scope.$samples = $('#samples')
scope.$header = $('#header')
var $generator = scope.$generator = $('#generator')
var $focus = null
var inputs = {}
$generator.data('active', false)
$generator.data('top', $generator.offset().top)
$generator.data('$focus', $focus)
$.each(['balls', 'periods', 'heights'], function (index, item) {
var $item = inputs['$' + item] = $('#' + item)
if (native_android_browser)
$item.addClass('android-browser')
var $keys = $('#keyboard-' + item)
if (item === 'periods') {
$keys.keyboard(range(1, 10), function (key) {
return '<span class="numbers keyboard-btn number-' + key + '">' + key + '</span>'
})
} else {
$keys.keyboard(range(1, 25), function (key) {
return '<span class="numbers keyboard-btn number-' + key + '">' + key + '</span>'
})
}
$.each(['min', 'max'], function (index, sufix) {
var $elem = $('#' + item + '-' + sufix)
$item.data('$' + sufix, $elem)
$elem.data('$parent', $item)
var width = $elem.width()
$elem.width(width)
var minWidth = '40px'
$elem.data('width', width)
$elem.data('min-width', minWidth)
$elem.data('type', item)
$elem.data('minmax', sufix)
$elem.data('$keys', $keys)
})
validatorHandler($item, item, index)
})
var $simulator = scope.$simulator = $('#simulator')
$simulator.data('active', false)
$generator.data('inputs', inputs)
for (var key in buttons) {
var $item = buttons[key]
$item.on('click', '.keyboard-btn', $item, function (event) {
var $this = $(this)
var $item = event.data
var $select = $item.data('$select')
if ($select) {
deselectButton($select)
}
$item.data('$select', $this)
selectButton($this, $item)
})
}
function rec() {
var first = $('li', scope.$samples).slice(0, 1)
scope.$samples.animate({
'margin-left': - first.width()
}, DELAY, 'swing', function () {
scope.$samples.css('margin-left', 0)
first.detach()
scope.$samples.append(first)
})
setTimeout(rec, 10000)
}
rec()
function createPatterns(event, scope) {
scope = scope || event.data
var $keyboard = scope.$keyboard
var $simulator = scope.$simulator
var $generator = scope.$generator
var array = [
inputs.$balls,
inputs.$periods,
inputs.$heights
]
var params = $.map(array, function($item) {
return {
min: parseInt($item.data('$min').text()) || undefined,
max: parseInt($item.data('$max').text()) || undefined
}
})
//console.log('CREATE PATTERN')
var patterns = siteswapGenerator.apply(null, params)
patterns = patterns.map(function (pattern) {
return pattern.map(function (e) {
return heightToLetter[e]
}).join('')
})
$simulator.data('patterns', patterns)
buttons.$patterns.keyboard(patterns, function (pattern) {
return '<a class="keyboard-btn" href="#simulator?play=' + pattern + '">' + pattern + '</a>'
})
if (scope.juggler) {
scope.juggler.stop()
}
scope.jugglerPlaying = false
buttons.$patterns.data('active', false)
buttons.$patterns.data('position', 0)
buttons.$patterns.css('left', 0)
buttons.$patterns.data('width', null)
return patterns
}
scope.$create.on('click', scope, createPatterns)
scope.$root.on('click', $generator, function (event) {
//console.log('jijiji')
var $generator = event.data
var $focus = $generator.data('$focus')
if ($focus) {
triggerDelegatedEvent('blureditable', $generator, $focus[0])
$generator.data('$focus', null)
}
})
$generator.on('click', '.editable', $generator, function (event) {
event.stopPropagation()
var $generator = event.data
var $focus = $generator.data('$focus')
if ($focus) {
triggerDelegatedEvent('blureditable', $generator, $focus[0])
}
$focus = $('.contenteditable', this).first()
$generator.data('$focus', $focus)
triggerDelegatedEvent('focuseditable', $generator, $focus[0])
})
$generator.on('click', '.contenteditable', $generator, function (event) {
event.stopPropagation()
var $generator = event.data
var $focus = $generator.data('$focus')
if ($focus) {
triggerDelegatedEvent('blureditable', $generator, $focus[0])
}
$focus = $(this)
$generator.data('$focus', $focus)
triggerDelegatedEvent('focuseditable', $generator, this)
})
function selectButton($button, $context, onlymove) {
if (!onlymove) {
$button.addClass('select')
$context.data('$select', $button)
}
var minmax = $button.data('minmax')
//console.log('minmax', minmax, $button[0])
var width = $context.data('width')
if ($context.outerWidth() > $keyboard.outerWidth()) {
//console.log($(window).outerWidth(), $button.outerWidth(), $button.offset().left)
var diff = 0.5 * ($(window).outerWidth() - $button.outerWidth()) - $button.offset().left
var pos = $context.data('position') + diff
if (pos < -width)
pos = -width
else if (pos > 0)
pos = 0
$context.data('position', pos)
$context.css('left', pos)
}
}
function deselectButton($button, onlymove) {
if (!onlymove) {
$button.removeClass('select')
}
}
$generator.on('focuseditable', '.contenteditable', $keyboard, function (event) {
var $keyboard = event.data
var $this = $(this)
var $keys = $this.data('$keys')
var $parent = $this.data('$parent')
var $shown = $keyboard.data('$shown')
var minmax = $this.data('minmax')
$parent.addClass('expanded')
if ($parent.hasClass('minEqMax'))
visible('minEqMax', $parent)
if ($parent.hasClass('minLessOrEq1'))
visible('minLessOrEq1', $parent)
$this.addClass('select')
var width = $keys.data('width')
if (!width) {
width = $keys.width() - $keyboard.outerWidth() + 120
$keys.data('width', width)
}
$keyboard.removeClass('hide')
$keyboard.data('$shown', $keys)
$keys.addClass('select')
$keys.data('active', true)
var num = parseInt($this.text().trim())
var oposite
var onlymove = false
if (minmax === 'min') {
oposite = parseInt($parent.data('$max').text().trim())
if (num > oposite) {
num = oposite
onlymove = true
console.log('onlymove')
}
} else {
oposite = parseInt($parent.data('$min').text().trim())
if (num < oposite) {
num = oposite
onlymove = true
console.log('onlymove')
}
}
var $select = $keys.data('$select')
if ($select && !$select.hasClass(className)) {
deselectButton($select)
}
if (num) {
var className = 'number-' + num
selectButton($('.' + className, $keys), $keys, onlymove)
}
})
function visible (className, $context) {
console.log('visible')
$context.removeClass(className)
}
function collapse (className, $context) {
console.log('collapse')
$context.addClass(className)
}
function editableHandler (min, max, $context) {
var added = false
if (!added && min === max) {
collapse('minEqMax', $context)
added = true
} else {
visible('minEqMax', $context)
}
if (!added && min <= 1 || min === undefined) {
collapse('minLessOrEq1', $context)
added = true
} else {
visible('minLessOrEq1', $context)
}
if (added) {
$context.removeClass('expanded')
} else {
$context.addClass('expanded')
}
}
$generator.on('blureditable', '.contenteditable', scope, function (event) {
console.log('blureditable')
var $this = $(this)
var scope = event.data
var $keyboard = scope.$keyboard
var $keys = $this.data('$keys')
var $shown = $keyboard.data('$shown')
var $parent = $this.data('$parent')
var minText = $parent.data('$min').text()
var maxText = $parent.data('$max').text()
editableHandler(minText, maxText, $parent)
$this.removeClass('select')
if ($shown) {
$keyboard.addClass('hide')
$keys.removeClass('select')
//numbers.$item = shown.$item
//$keyboard.shown = undefined
}
$keys.data('active', false)
})
function inputHandler (event) {
var scope = event.data
var $this = $(this)
var type = $this.data('type')
var minmax = $this.data('minmax')
values[type][minmax] = parseInt($this.text()) || undefined
validate(values, type, minmax, 'all')
if (!errorHandler.ok())
console.log(errorHandler.message())
generateText[type](text, values[type], scope.outputs[type])
if (!errorHandler.ok()) {
scope.message.$success.addClass('hide')
scope.message.$error.text(errorHandler.message())
scope.message.$error.removeClass('hide')
} else {
scope.message.$error.addClass('hide')
scope.message.$success.removeClass('hide')
}
if (!errorHandler.ok()) {
scope.$create.addClass('disabled')
scope.$wrapper.addClass('simulator-disabled')
} else {
scope.$create.removeClass('disabled')
scope.$wrapper.removeClass('simulator-disabled')
}
}
$generator.on('inputeditable', '.contenteditable', scope, inputHandler)
var width
function validatorHandler($item, type, index) {
var $min = $item.data('$min')
var $max = $item.data('$max')
var minText = $min.text()
var maxText = $max.text()
var textError
editableHandler(minText, maxText, $item)
values[type] = {
min: parseInt(minText) || undefined,
max: parseInt(maxText) || undefined
}
validate(values, type, 'min')
if (!errorHandler.ok()) {
scope.message.$error.text(textError)
scope.message.$success.addClass('hide')
}
//console.log('min', values[type].min)
validate(values, type, 'max', index === 2 ? 'all' : 'range')
if (!errorHandler.ok()) {
scope.message.$error.text(textError)
scope.message.$success.addClass('hide')
}
//console.log('max', values[type].max)
generateText[type](text, values[type], scope.outputs[type])
if (!errorHandler.ok()) {
scope.$create.addClass('disabled')
scope.$wrapper.addClass('simulator-disabled')
} else {
scope.$create.removeClass('disabled')
scope.$wrapper.removeClass('simulator-disabled')
}
}
/*$.each(['balls', 'periods', 'heights'], function (index, type) {
var $item = inputs['$' + type]
})*/
$keyboard.on('click', function (event) {
event.stopPropagation()
})
$left.on('click', $keyboard, function (event) {
var $keyboard = event.data
var $shown = $keyboard.data('$shown')
if ($shown.outerWidth() > $keyboard.outerWidth()) {
var width = $keyboard.width() - 100
var pos = $shown.data('position') + width
pos = Math.min(pos, 0)
$shown.data('position', pos)
$shown.css('left', pos)
}
})
$right.on('click', $keyboard, function (event) {
var $keyboard = event.data
var $shown = $keyboard.data('$shown')
if ($shown.outerWidth() > $keyboard.outerWidth()) {
var width = $keyboard.width() - 100
var pos = $shown.data('position') - width
pos = Math.max(pos, -$shown.data('width'))
$shown.data('position', pos)
$shown.css('left', pos)
}
})
function clickLinkHandler (event) {
event.preventDefault()
var scope = event.data
var $keyboard = scope.$keyboard
var $simulator = scope.$simulator
var href = parseHref($(this).attr('href'), {
fragment: '#header'
})
var oldQueryString = scope.href.queryString
var newQueryString = href.queryString
var targetTop = $(href.fragment).offset().top
scope.$root.animate({scrollTop: targetTop}, DELAY, 'swing')
if (href.fragment === "#header") {
$keyboard.addClass('hide')
var $shown = $keyboard.data('$shown')
if ($shown) {
$shown.removeClass('select')
}
} else {
if (href.fragment === "#simulator") {
var patterns = $simulator.data('patterns')
if (!patterns) {
patterns = createPatterns({}, scope)
}
href.queryString.play = href.queryString.play || patterns[0]
console.log('play', href.queryString.play)
if (!scope.juggler) {
scope.juggler = new Juggler({
stage: {
container: 'juggler-simulator',
width: $simulator.width(),
height: $simulator.height()
}
})
}
if (oldQueryString.play !== newQueryString.play) {
scope.juggler.stop()
scope.juggler.setPattern(href.queryString.play)
scope.juggler.play()
scope.jugglerPlaying = true
}
}
}
scope.href = href
}
scope.$root.on('click', '.internal-link.disabled', function (event) {
event.preventDefault()
})
scope.$root.on('click', '.internal-link:not(.disabled)', scope, clickLinkHandler)
buttons.$patterns.on('click', 'a:not(.disabled)', scope, clickLinkHandler)
$keyboard.on('click', '.keyboard-btn.numbers', $generator, function (event) {
var num = parseInt($(this).text())
var $generator = event.data
var $focus = $generator.data('$focus')
$focus.text(num)
triggerDelegatedEvent('inputeditable', $generator, $focus[0])
})
$(window).on('scroll', scope, function (event) {
var scope = event.data
var $generator = scope.$generator
var $simulator = scope.$simulator
var top = $(window).scrollTop()
var topGenerator = $generator.offset().top
var topSimulator = $simulator.offset().top
if (top < topGenerator - 50) {
scope.$header.removeClass('reduce')
} else {
scope.$header.addClass('reduce')
}
var active = $generator.data('active')
if (active && (top < topGenerator - 50 || top >= scope.topCreate)) {
$generator.trigger('off')
$generator.data('active', false)
} else if (!active && (top >= topGenerator - 50 && top < scope.topCreate)){
$generator.trigger('on')
$generator.data('active', true)
}
active = $simulator.data('active')
//console.log(top, topSimulator, active)
if (active && top < topSimulator - 50) {
$simulator.trigger('off')
$simulator.data('active', false)
} else if (!active && !$wrapper.hasClass('simulator-disabled') && top >= topSimulator - 50) {
$simulator.trigger('on')
$simulator.data('active', true)
}
})
$simulator.on('off', $keyboard, function (event) {
//console.log('OFF simulator')
var $keyboard = event.data
var $shown = $keyboard.data('$shown')
var buttons = $keyboard.data('buttons')
buttons.$patterns.removeClass('select')
if ($shown) {
$shown.removeClass('select')
$keyboard.data('$shown', null)
}
$keyboard.addClass('hide')
})
$generator.on('off', $keyboard, function (event) {
//console.log('OFF generator')
var $keyboard = event.data
var $shown = $keyboard.data('$shown')
if ($shown) {
$shown.removeClass('select')
$keyboard.data('$shown', null)
}
$keyboard.addClass('hide')
})
$simulator.on('on', scope, function (event) {
console.log('ON simulator')
var scope = event.data
var $keyboard = scope.$keyboard
var $shown = $keyboard.data('$shown')
var buttons = $keyboard.data('buttons')
var href = scope.href
var $simulator = scope.$simulator
var patterns = $simulator.data('patterns')
if (!patterns) {
patterns = createPatterns({}, scope)
}
if (!scope.jugglerPlaying) {
href.queryString.play = href.queryString.play || patterns[0]
if (!scope.juggler) {
scope.juggler = new Juggler({
stage: {
container: 'juggler-simulator',
width: $simulator.width(),
height: $simulator.height()
}
})
}
scope.juggler.stop()
scope.juggler.setPattern(href.queryString.play)
scope.juggler.play()
scope.jugglerPlaying = true
}
if ($shown) {
$shown.removeClass('select')
}
$shown = buttons.$patterns
$keyboard.data('$shown', $shown)
$shown.addClass('select')
$keyboard.removeClass('hide')
var width = buttons.$patterns.data('width')
if (!width) {
width = buttons.$patterns.width() - $keyboard.outerWidth() + 120
buttons.$patterns.data('width', width)
}
})
$generator.on('on', scope, function (event) {
//console.log('ON generator')
var scope = event.data
var $focus = scope.$generator.data('$focus')
var $keyboard = scope.$keyboard
var $shown = $keyboard.data('$shown')
var buttons = $keyboard.data('buttons')
if ($shown) {
$shown.removeClass('select')
$keyboard.data('$shown', null)
}
if ($focus) {
$shown = $focus.data('$keys')
$keyboard.data('$shown', $shown)
$shown.addClass('select')
$keyboard.removeClass('hide')
}
})
})
|
81b2ddb0962957859f5a2900dc6b348c6d4af471
|
[
"JavaScript"
] | 2
|
JavaScript
|
xgbuils/ca-juggol
|
e1155edd62507468b409be2243c18e54a76bbb60
|
09f806eeccc69fb8866c4209351ef3669b54aa26
|
refs/heads/master
|
<file_sep>Cleaning data method :
1) When we read features.txt and activity_labels.txt files we remove the unecessary columns.
2) When we merge the test and the train files we name the variables by using features.txt file. We name the first column Subject.Number and the second one Activity.
3) In order to filter out only the columns that describe a mean or a st. deviation , we filter all the columns that have "std" or "mean" in their names.
4) We then rename the activities 1,2,3,4,5,6 to
"WALKING","WALKING_UPSTAIRS","WALKING_DOWNSTAIRS","SITTING","STANDING","LAYING" resepctively.
5)We rename the columns so they become readble by humans. All the columns containing :
"BodyAcc" are replaced with "Body_Acceleration"
"GravityAcc" are replaced with "Gravity_Acceleration"
"BodyGyro" are replaced with "Body_Gyroscope"
"BodyGyroMag" are replaced with "Body_Gyro_Magnitude"
"JerkMag" are replaced with "Jerk_Magnitude"
"t_" are replaced with "Time_"
"f_" are replaced with "Frequency_"
6) Finally , we create a new tidy dataset containing the mean of the variables per subject per activity.
With all the variables, the data has been divided by its range (gyroscope, entropy, etc) to normalise it. When we divide something with a set of units by something else using the same set of units, the units are cancelled out leaving us with a ratio
<file_sep>library(jpeg)
library(plyr)
library(Hmisc)
## Setting working directory :
setwd("C:/Users/Eddie-Main/Desktop/R data folder/CleaningData/UCI HAR Dataset")
##Reading in the features.txt and activity_labels file:
features <- read.table("features.txt",stringsAsFactors=FALSE, sep="")
labels <- read.table("activity_labels.txt",stringsAsFactors=FALSE, sep="")
#Cleaning features.txt and activity_labels.txt (removing unnessesary column)
features <- features$V2
labels <- labels$V2
#Readng test data:
X_test = read.table("./test/X_test.txt", sep="")
Y_test = read.table("./test/y_test.txt", sep="")
subject_test = read.table("./test/subject_test.txt", sep="")
#Reading train data:
X_train = read.table("./train/X_train.txt", sep="")
Y_train = read.table("./train/y_train.txt", sep="")
subject_train = read.table("./train/subject_train.txt", sep="")
# labelling the data .
names(X_test) <- features
names(X_train) <- features
colnames(Y_test) <- c("Activity")
colnames(Y_train) <- c("Activity")
colnames(subject_test) <- c("Subject.Number")
colnames(subject_train) <- c("Subject.Number")
# Part 1 : Merges the training and the test sets to create one data set.
bind1<- cbind(subject_test,Y_test)
testdata <- cbind(bind1, X_test)
bind2<- cbind(subject_train,Y_train)
traindata <- cbind(bind2, X_train)
alldata <- rbind(testdata,traindata)
#Part 2 : Mean and st.dev for each variable, we use the grepl function to find all the column names
#which contain "mean" or "std" in the strings.
meanstd<-alldata[,c(1,2,grepl("mean",names(alldata))==TRUE | grepl("std",names(alldata))==TRUE)]
meanstd<-alldata[,grepl("mean",names(alldata))==TRUE | grepl("std",names(alldata))==TRUE]
meanstd<- cbind(alldata[,1:2],meanstd)
#Part 3 : Using descriptive activity names to name the activities in the data set
alldata$Activity <-gsub("1", "WALKING", alldata$Activity)
alldata$Activity <-gsub("2", "WALKING_UPSTAIRS", alldata$Activity)
alldata$Activity <-gsub("3", "WALKING_DOWNSTAIRS", alldata$Activity)
alldata$Activity <-gsub("4", "SITTING", alldata$Activity)
alldata$Activity <-gsub("5", "STANDING", alldata$Activity)
alldata$Activity <-gsub("6", "LAYING", alldata$Activity)
#Part 4: Appropriately labels the data set with descriptive variable names.
names(alldata) <- gsub("BodyAcc", "_Body_Acceleration_", names(alldata))
names(alldata) <- gsub("GravityAcc", "_Gravity_Acceleration_", names(alldata))
names(alldata) <- gsub("BodyGyro", "_Body_Gyroscope_", names(alldata))
names(alldata) <- gsub("BodyGyroMag", "_Body_Gyroscope_Magnitude_", names(alldata))
names(alldata) <- gsub("JerkMag", "_Jerk_Magnitude_", names(alldata))
names(alldata) <- gsub("t_", "Time_", names(alldata))
names(alldata) <- gsub("f_", "Frequency_", names(alldata))
names(alldata) <- gsub("fBody", "Frequency_", names(alldata))
#Part 5 : Creates a second, independent tidy data set with the average of each variable for each activity and each subject.
tidydata <-ddply(meanstd,.(Subject.Number,Activity),numcolwise(mean))
#Writing tidy dataset to tidydata.txt
write.table (tidydata, file = "tidydata.txt", sep = " ")
<file_sep>Course-Project---Cleaning-Data--Coursera-
=========================================
run_analysis.R reads in to R and merges the .txt files (X_test, y_test, subject_test, X train , Y_train, subject_train).
It cleans the dataset and outputs a new tidy dataset as tidydata.txt with the means of all variables per activity per subject. In CodeBook.md file you can see the methodology used in cleaning the data.
Course Project : Cleaning Data (Coursera)
|
31a0a3affd3884f3cfe4295468dd5a1d9553fb9f
|
[
"Markdown",
"R"
] | 3
|
Markdown
|
eddiebeherano/Course-Project---Cleaning-Data--Coursera-
|
cdf63e63088f4231684e43870d38ed82c755c8c3
|
c636d45ba4b6b3a6a6576e21732a6b1c12ff9b84
|
refs/heads/main
|
<repo_name>aureliengremy/rpg-VIF<file_sep>/README.md
# rpg-VIF
RPG classique avec les VIF
##### Source and Idea for this project :
- [link to article from freeCodeCamp](https://www.freecodecamp.org/news/learning-javascript-by-making-a-game-4aca51ad9030/ "built a role playing game")
## git :
- Create gitignore
- Remove node_modules
Création des fichiers nécessaire | Init npm and Git
## npm :
- init and config (simple)
---
NOTE :
#### Idée simple et facile :
- Monter un questionnaire pour le choix de chacun (pouvoir et autres spécificité)
- Monter liste d'info de chaque personnage
- Penser à la sélection du personnage
> "Never Stop"
<file_sep>/js/script.js
class Personnage {
constructor(nom, classes, signe, sante, attaque) {
this.nom = nom;
this.classes = classes;
this.signe = signe;
this.sante = sante;
this.attque = attaque;
}
}
// --- Element - Variable --- //
// -> Sante
var upperLife = document.querySelector('.progress-upper');
let downLife = document.querySelector('.progress-down');
|
34d151a6cc751d6f0a9156c32a717b87ac1e8c0f
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
aureliengremy/rpg-VIF
|
ccbd3b74fc578627f6bbfcd5504868ce24d5c139
|
9538a9fe88f36e9015693b7fccfed2bf7b47b360
|
refs/heads/main
|
<file_sep>
package idiomadosistema;
import java.util.Locale;
/**
*
* @author <NAME>
*/
public class IdiomaDoSistema {
public static void main(String[] args) {
Locale sis = Locale.getDefault();
System.out.println("O seu sistema está em");
System.out.println(sis.getDisplayLanguage());
}
}
<file_sep># IdiomaDoSistema
Programa que busca o idioma configurando na maquina
|
2942d5d81b12b2f496525342d0d3f79945445a60
|
[
"Markdown",
"Java"
] | 2
|
Java
|
michaelcoitim/IdiomaDoSistema
|
2ea31e772c47df5ef80da20301a44d5209ffbbec
|
9a4d0ac08aa507f154dc34a7aca1cbce02ada598
|
refs/heads/master
|
<file_sep>Trong bài này mình sẽ giới thiệu cho các bạn cách để khởi tạo một website đơn giản với Node JS.
# 1. Kiến thức cần biết
Để học bài này các bạn nên đọc trước hai bài viết của mình đó là thể nào là một web server và giao thức HTTP là gì.
1) [Giao thức HTTP là gì ? ](https://sociss.edu.vn/courses/nodejs/lesson/giao-thuc-http-la-gi)
2) [Webserver là gì ?](https://sociss.edu.vn/courses/nodejs/lesson/web-server-la-gi)
Nắm hai khái niệm này các bạn sẽ dễ hiểu bài học đầu tiên này hơn.
# 2. Công cụ cần thiết
Các bạn cần cài đặt thành công **Node.js phiên bản v6.11** trở lên trên máy tính của mình. Thử đoạn lệnh dưới đây để kiểm tra xem mình đã cài thành công chưa nhé.
```sh
node -v
```
Nếu kết quả trả về là version của Node bạn cài đặt thì bạn đã cài thành công nếu không thì bạn hãy xem lại
bài viết hướng dẫn cài đặt môi trường làm việc của mình.
1) [Hướng dẫn cài đặt Node JS](https://sociss.edu.vn/courses/nodejs/lesson/huong-dan-cai-dat-nodejs)
2) [Cài đặt công cụ và thiết lập môi trường thực hành với Node JS](https://sociss.edu.vn/courses/nodejs/lesson/cai-dat-cong-cu-va-thiet-lap-moi-truong-thuc-hanh-voi-node-js)
Sau khi có đủ kiến thức nền cần thiết và công cụ rồi thì chúng ta cùng vào bài học chính nào.
# 3. Nội dung
## 3.1 Khởi tạo một HTTP Server
Đầu tiên sau khi khởi tạo xong một project Node thì bạn tạo một thư mục là **src/simple-website** trong thư mục này bạn tạo file `index.js` trong đó nhập đoạn mã dưới đây vào.
```javascript
"use strict";
let http = require('http');
const port = 3000;
// Step 1: Do create HTTP server.
let server = http.createServer(requestHandler);
// Step 2: Define handle function called each time we request server.
function requestHandler(request, response) {
const userAgent = request.headers['user-agent'];
// Print to console your browser information.
console.log(userAgent);
if(request.url === '/') {
return response.end('Hello Node.js Server!');
}
if(request.url === '/about') {
return response.end('This is about page!');
}
if(request.url === '/contact') {
return response.end('This is contact!');
}
}
// Step 3: Turn on server on port.
server.listen(port, function(err){
if (err) {
return console.error('Something bad happened', err);
}
console.log(`server is listening on ${port}`);
});
```
Đoạn mã trên đã khởi tạo một webserver HTTP lắng nghe ở cổng 3000 để tiếp nhận các request.Để ý trong đoạn mã trên mình lấy được thông tin của trình duyệt người dùng qua câu lệnh.
Mở trình duyệt của bạn lên, truy cập vào `127.0.0.1:3000` và xem kết quả. Sau đó lần lượt truy cập vào đường dẫn `127.0.0.1:3000/about` và `127.0.0.1:3000/contact` bạn sẽ thấy nội dung tương ứng.
Có thể thay 127.0.0.1 bằng localhost vẫn chạy được, tuy nhiên bạn có thể reseach thêm một chút để biết sự khác nhau giữa hai cái này nếu cần.
**Giải thích ý nghĩa câu lệnh quan trọng**
Như bạn đã biết trong bài học về giao thức HTTP, với một request tương ứng với một URL cụ thể thì server có nhiệm vụ đáp ứng request đó.
Ở đây `requestHandler` chính là phương thức đáp ứng đó, với mỗi request vào web server thì nó sẽ được gọi để đáp ứng các request.
```javascript
// Step 1: Do create HTTP server.
let server = http.createServer(requestHandler);
```
câu lệnh trên chính là câu lệnh tạo một HTTP webserver với requestHandler tương ứng.
Sau khi tạo xong thì web server vẫn chưa chạy, để chạy được web server chúng ta cần chỉ cho nó một cổng cụ thể để chạy. Vì qua bài học về [web server](https://sociss.edu.vn/courses/nodejs/lesson/web-server-la-gi) các bạn đã biết rằng một web server thật ra là một chương trình chạy ở một cổng cụ thể trên một máy tính.
```javascript
// Step 3: Turn on server on port.
server.listen(port, function(err){
if (err) {
return console.error('Something bad happened', err);
}
console.log(`server is listening on ${port}`);
});
```
Câu lệnh trên chính là để khởi chạy web server trên cổng 3000 để lắng nghe các request từ client.
Lúc này web server đã chạy ở cổng 3000 rồi, các bạn có thể truy cập đến nó bằng cách mở trình duyệt
và truy cập `127.0.0.1:3000` hoặc `localhost:3000`.
Để ý rằng 127.0.0.1 hoặc localhost lần lượt chính là địa chỉ IP và tên miền của chính máy tính các bạn đang sử dụng, và 3000 chính là sổ cổng chạy dịch vụ web server.
Lúc này đúng theo lý thuyết, web server sẽ tiếp nhận yêu cầu và trả về kết quả.
**Đi sâu hơn vào mã lệnh**
Đây chính là cách lấy phần header trong một gói tin. Ở dưới là mình lấy về thông tin về trình duyệt của người dùng.
```javascript
const userAgent = request.headers['user-agent'];
```
tiếp theo đó là phần xử lý tương ứng với các request vào trên mỗi URL cụ thể.
```javascript
if(request.url === '/about') {
return response.end('This is about page!');
}
```
Ở trên mình sẽ kiểm tra nếu Request URL là `/about` thì sẽ trả về chữ `This is about page!`. Trong trường hợp này vì không định nghĩa sẽ đáp ứng với Method nào nên nó sẽ đáp ứng với mọi method request. Ví dụ mình dùng `curl tool` để tạo một POST request đến URL `/about`
```sh
curl -XPOST "127.0.0.1:3000/about"
This is about page!
```
và kết quả mình nhận được như trên, để có thể xử lý request tương ứng với mỗi URL và Method cụ thể bạn có thể làm như sau, với một chút cải tiến là sẽ so sánh thêm method nữa,
```javascript
"use strict";
let http = require('http');
const port = 3000;
// Step 1: Do create HTTP server.
let server = http.createServer(requestHandler);
/**
* @name when
* @description
* Call handler method correct on path and method request.
*
* @param {object} req HTTP Request
* @param {object} res HTTP Response
* @param {string} path Path
* @param {string} method HTTP method
* @param {Function} callback handler function
*/
function when(req, res, path, method, callback) {
if(req.url === path && req.method === method) {
callback(req, res);
}
}
// Step 2: Define handle function called each time we request server.
function requestHandler(request, response) {
const userAgent = request.headers['user-agent'];
const requestMethod = request.method;
// Print to console your browser information.
console.log('User Agent : ' + userAgent);
console.log('Method :' + requestMethod);
when(req, res, '/', 'GET', function (req, res) {
return res.end('Hello Node.js Server!');
});
when(req, res, '/about', 'GET', function (req, res) {
return res.end('This is about page!');
});
when(req, res, '/contact', 'GET', function (req, res) {
return res.end('This is contact page!');
});
}
// Step 3: Turn on server on port.
server.listen(port, function(err){
if (err) {
return console.error('Something bad happened', err);
}
console.log(`server is listening on ${port}`);
});
```
Với cải tiến lại như trên bạn đã có thể xử lý tốt hơn rồi. Và ở trên chính là ví dụ tạo một HTTP server đơn giản để xử lý các request của người dùng.
## 3.2 Về Module HTTP
Như ví dụ ở trên về Module HTTP của Node. Module này có các Class giúp ta thực hiện một số công việc dưới đây.
**1) Tạo ra một HTTP server**
Như là ví dụ ở trên mình dùng `Class: http.Server`
**2) Thực hiện các Request**
Việc này ta dùng `Class: http.ClientRequest`, để thực hiện các request HTTP đến các máy chủ, ví dụ như đoạn mã dưới đây sẽ request đến máy chủ của Sociss Class ở cổng 80. Các bạn tạo ra file mới tên là `HttpRequestDemo.js` rồi điền vào đó đoạn mã dưới đây.
```javascript
const http = require('http');
const options = {
port: 80,
method : 'GET',
hostname: 'sociss.edu.vn'
};
const req = http.request(options);
req.setHeader('Content-Type', 'text/html');
// res is http.IncomingMessage
req.on('response', (res) => {
// 200 Ok
console.log(res.statusCode + ' '+ res.statusMessage);
console.log(res.rawHeaders);
});
// Start request.
req.end();
```
Khi chạy thực hiện đoạn file `HttpRequestDemo.js`, khi đó callback sẽ nhận lại một `http.IncomingMessage`. Là một gói tin HTTP, trong này mình sẽ lấy ra Status Code và phần headers sau đó in giá trị ra console.
**3) Đáp ứng ( Response )**
Đối tượng `response` trong các ví dụ trước đó là `http.ServerResponse`, đối tượng này bạn không tự tạo ra được mà nó sẽ được tạo bởi Node.js. Tuy nhiên khi có đối tượng này rồi thì bạn sẽ có một số hành động thường làm như là thiết lập response headers, body message, ...
```javascript
response.writeHead(200, { 'Content-Type': 'text/plain'});
response.write('DATA NEED TO TRANSFER');
response.end();
```
# 4. Nhận xét và kết luận
Qua bài học trên mình đã giới thiệu cho các bạn cách để tạo một HTTP webserver đơn giản với Module HTTP. Các bạn có thể áp dụng ví dụ trên để xây dựng một webserver đơn giản và nhẹ nhàng (Rất có ích cho các ứng dụng IOT đơn giản), đồng thời cũng giúp bạn hiểu bản chất một HTTP server trực quan hơn.
Tuy nhiên nếu bạn cần xây dựng một website lớn hơn phức tạp hơn thì cách làm với Module HTTP như trên sẽ không hiệu quả.
Thì để khắc phục nhược điểm ấy mình sẽ sử dụng một framework đó là [Express JS](http://expressjs.com/). Đây là một Framework giúp cho việc xây dựng một trang web trở nên đơn giản hơn và nhanh hơn.
Bài tiếp theo mình sẽ hướng dẫn cách xây dựng một trang web tĩnh với Express JS.
# 5. Bài tập
Trước khi có bài học tiếp theo, các bạn hãy làm lại những ví dụ trên và đọc thêm tài liệu về Module HTTP nếu cần theo URL sau [HTTP Module Node.js](https://nodejs.org/api/http.html).
Mã nguồn của bài học này mình để ở Github với URL là [Create Simple HTTP Webserver](https://github.com/nghuuquyen/sociss-class-nodejs/tree/master/src/simple-website)
# Tác giả
**Name:** <NAME> ( <NAME> )
**Email:** <EMAIL>
**Website:** [Sociss Class - Online Education Center](https://sociss.edu.vn/)
**Profile Page:** [<NAME> - Profile Page ](https://sociss.edu.vn/users/nghuuquyen)
<file_sep>console.log('1. Demo For Loop.');
for(var i=0; i<= 5; i++) {
console.log(i);
}
console.log('2. For loop item in array.');
var arrays = ['A', 'B', 'C', 'D', 'E'];
for(var item in arrays) {
console.log(arrays[item]);
}
console.log('3. For each function of arrays.');
arrays.forEach(function onEachItem(_item) {
console.log(_item);
});
console.log('4. Arrow function for forEach.');
arrays.forEach(_item => {
console.log(_item)
});
<file_sep>"use strict";
function test_1() {
if(true) {
let num = 10;
}
console.log(num);
}
function test_2() {
for(let i = 0; i <= 10; i++) {
console.log(i);
}
}
function test_3() {
outerloop: // This is the label name
for (var i = 0; i < 3; i++) {
console.log("Outerloop: " + i);
for (var j = 0; j < 5; j++) {
if (j == 3){
continue outerloop;
}
console.log("Innerloop: " + j );
}
}
}
function test_4(){
function Fun() {
return {
message : 'Yahhh'
};
}
var a = Fun();
var b = Fun();
b.message = 'Change';
console.log(a.message);
}
function test_5(){
function Fun() {
console.log(this);
return this;
}
var a = Fun();
var b = Fun();
var a2 = new Fun();
var b2 = new Fun();
console.log(a === b);
console.log(a2 === b2);
}
function test_6(){
function Fun() {
return {};
}
var a = Fun();
var b = Fun();
a.message = 'Hello World';
console.log(b.message);
var a2 = new Fun();
var b2 = new Fun();
console.log(a === b);
console.log(a2 === b2);
}
function test_7() {
console.log(_messageGlobal);
}
var _messageGlobal = 'Hello, i have hosting';
function test_8() {
for(let i=0; i<10000000; i++) {
(function() {
})();
}
}
test_7();
<file_sep>function A() {
return new Promise((resolve, reject) => {
resolve('A successfully');
});
}
function B() {
return new Promise((resolve, reject) => {
resolve('B successfully');
});
}
A().then(B).then(result => {
console.log('Done');
console.log('Result: ' + result);
});
<file_sep>#hello-world
Ví dụ này chỉ đơn giản là in ra console dòng chữ là "Hello World". Tuy nhiên đây cũng nên là một ví dụ đơn giản nhất để thử nghiệm Node JS có hoạt động tốt hay không.
<file_sep>alert('Yeah !!!, you got me');
var x = document.getElementById("pTag");
x.innerHTML = "Content change by app.client.js !!!";
<file_sep>/**
* @author <NAME>
* @module controller
* @name author.server.controller
*/
"use strict";
let Services = require('../services');
let AuthorService = Services.Author;
let PostService = Services.Post;
module.exports = {
findOne : findAuthorByUsernameOrId,
renderAuthorPage : renderAuthorPage,
renderAuthorPostsPage : renderAuthorPostsPage
};
/**
* @name renderAuthorPage
* @description
* Render HTTP page for view author information.
*
* @param {object} req HTTP request
* @param {object} req.author Author selected.
* @param {object} res HTTP response
*/
function renderAuthorPage(req, res) {
res.render('author/view', {
author : req.author
});
}
/**
* @name renderAuthorPostsPage
* @description
* Render HTTP page list all posts of selected author.
*
* @param {object} req HTTP request
* @param {object} req.author Author selected.
* @param {object} res HTTP response
* @param {object} next Next middleware
*/
function renderAuthorPostsPage(req, res, next) {
PostService.findPostsByAuthor(req.author.id).then(_posts => {
res.render('author/posts', {
author : req.author,
posts : _posts
});
})
.catch(err => next(err));
}
/**
* @name findAuthorByUsernameOrId
* @description
* Populate author data to HTTP request.
*
* @param {object} req HTTP request.
* @param {object} res HTTP response.
* @param {object} next Next middleware
* @param {object} author Author id or username.
*/
function findAuthorByUsernameOrId(req, res, next, author) {
AuthorService.findByUsernameOrId(author)
.then(_author => {
req.author = _author;
return next();
})
.catch(err => next(err));
}
<file_sep>require('./ForLoop');
require('./SwitchCase');
require('./JSON');
require('./IfElse');
<file_sep>module.exports = {
Author : require('./author.server.service'),
Post : require('./post.server.service')
};
<file_sep># 1. Giới thiệu
Chào các bạn, lần này mình sẽ giới thiệu đến các bạn chi tiết hơn về kỹ thuật Routing ( Định tuyến ) trong Node.js. Định tuyến đơn giản mà nói là xác định Client sẽ được đáp ứng như thế nào khi truy cập vào một liên kết với một HTTP method cụ thể.
## 1.1 Cấu trúc bài học
### Lý thuyết
Cấu trúc bài gồm 3 phần lý thuyết nói về 3 khái niệm chính là route path, route parameters và route response.
### Thực hành
Phần thực hành mình sẽ hướng dẫn cách áp dụng kỹ thuật Routing để xây dựng một trang web nhỏ theo mô hình MVC như hình dưới đây.
# 2. Kiến thức và công cụ cần thiết
## 2.1 Kiến thức
Trong bài học lần này là phân nâng cao của bài học trước, chính vì vậy mình mong muốn các bạn hiểu nội dùng trong bài học này trước, sau đó hãy tiếp tục đọc đến bài này.
Bài học trước [Tạo website đầu tiên với Node.js](https://sociss.edu.vn/courses/nodejs/lesson/tao-website-dau-tien-voi-nodejs)
## 2.2 Công cụ
Vẫn như những bài học trước, chúng ta vẫn chỉ cần máy tính cài đặt Node.js và một text editor là được.
# 3. Nội dung bài học
## 3.1 Routing là gì ?
Routing trong Node.js là một khái niệm nói đến việc xác định ứng dụng sẽ đáp ứng như thế nào khi người dùng tạo một request đến một endpoint (Điểm cuối) cụ thể nào đó. Điểm cuối đó thường là một URI hoặc một đường dẫn (Path) với một Request method (POST, PUT, GET, ...) cụ thể.
## 3.2 Cấu trúc định tuyến cơ bản
Trong express.js định tuyến có cấu trúc như sau
`app.METHOD(Path, Handler...)`
Trong đó:
+ **app** : là một instance của express
+ **METHOD**: là một HTTP Method
+ **Path**: là một đường dẫn trên máy chủ
+ **Handler** : là một function sẽ thực thi khi một **route** được trùng khớp
**Giải thích**
1) **handler** : có thể có một hoặc nhiều function
2) một **route** được xác định bằng Path (đường dẫn) và request method.
3) Khái niệm **route** trùng khớp là chỉ việc một người dùng thực hiện request với Path (đường dẫn) và Method trùng khớp với định nghĩa trong **route**.
Ví dụ ra có một route như sau
```javascript
app.get('/hello', function doHello(req, res) {
res.send('Hello World!')
})
```
Thì khi đó nếu client thực hiện một GET /hello đến máy chủ, thì khi ấy route sẽ trùng khớp và function doHello sẽ được gọi thực hiện.
## 3.2 Route methods
Express hỗ trợ rất nhiều loại HTTP methods khác nhau, bao gồm :
get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, patch and searc
Trong đó sử dụng nhiều nhất là:
Get, Post, Put, Head, Delete và Options ý nghĩa của từng method này mình đã nói đến trong bài học giao thức HTTP là gì.
## 3.3 Route paths (Đường dẫn)
Đây là phần trọng tâm của bài học hôm nay, route path có thể là một chuỗi thông thường (String) hoặc là một chuỗi có ký hiệu biểu thức chính quy (string patterns) hoặc là một biểu thức chính quy (regular expressions). Ví dụ
1) /users/nghuuquyen : là một đường dẫn thông thường
2) /users/user/* : là một đường dẫn với ký hiệu * biểu diễn cho một chuỗi bất kỳ
3) /^[a-zA-Z0-9]{5,15}$/ : là một đường dẫn có dạng biểu thức chính.
```javascript
app.get('/users/nghuuquyen', function(req, res) {
//Do something.
});
```
là một đường dẫn thông thường.
```javascript
app.get('/users/*', function(req, res) {
// Do something.
});
```
là một đường dẫn theo khuôn mẫu (String pattern). Ký hiệu * ở đây nói lên là route trên khớp với mọi đường dẫn bắt đầu với /users/.
```javascript
app.get(/.*cool$/, function(req, res) {
// Do something.
});
```
là một đường dẫn với dạng biểu thức chính quy (regular expression). Route này sẽ khớp với mọi đường dẫn kết thúc với đuôi là cool. Ví dụ YOUARESOcool sẽ khớp nhưng YOUTOOCool thì sẽ không vì khác ký tự 'C'.
**Ứng dụng**
Mình sẽ nêu một số ứng dụng với từng loại mà mình hay dùng trong quá trình lập trình.
+ Kiểu string pattern mình hay áp dụng để việc đánh chặn tất cả các route, dùng trong việc bảo vệ một tập đường dẫn nào đó, ví dụ
```javascript
app.get('/secure/*', coreCtrl.requireLogin);
```
Ví dụ như với mọi đường dẫn bắt đầu bằng /secure/ thì phải yêu cầu login.
+ Biểu thức chính quy thì mình hay dùng để validate (hợp thức hóa) các đối số, ví dụ
```javascript
router.route('/author/:author([a-zA-Z0-9.\-_]{8,30})').get(AuthorCtrl.renderAuthorPage);
```
Ở trên là một dạng đường dẫn với tham số :author được quy định có độ dài từ 8 đến 30 ký tự, bao gồm các chữ cái từ a-z, A-Z, 0-9 và 3 ký tự .,- và _. Nếu ở vi phạm thì route sẽ không khớp.
## 3.4 Route parameters
Route parameters là những vị trí trên URL được đánh dấu bằng cách đặt tên, mục đích là để lấy ra các giá trị tương ứng. Tất cả cá giá trị đối số sẽ được đặt vào đối tượng **req** trong thuộc tính **params**. Với tên thuộc tính trùng khớp với từ khóa được xác định trên URL.
Ví dụ, chúng ta định nghĩa một path là /users/:user . Thì ở đây :user chính là một route param. Khi đó nếu người dùng truy cập đường dẫn như là
/users/nghuuquyen --> ta lấy ra được :user = nghuuquyen
và giá trị này sẽ nằm ở req.params.user
```javscript
// Route path: /users/:user/:view
// Request URL: http://1172.16.31.10:3000/users/nghuuquyen/gallery
// req.params: { "user": "nghuuquyen", "view": "gallery"}
app.route('/users/:user/:view', function(req, res) {
console.log(req.params.user);
console.log(req.params.view);
});
```
**Ứng dụng**
Route parameter dùng để biết được client muốn truy vấn cái gì thông qua đối số truyền vào. Dựa vào đó trong function handler tương ứng, chúng ta sẽ lấy các giá trị ra và thực hiện truy vấn phù hợp.
Ví dụ:
Path: /user/:user
Request: /user/nghuuquyen
-> Trả về trang profile của người dùng có username là nghuuquyen.
**Kỹ thuật nâng cao**
1) Thường thì mình hay kết hợp rằng buộc biểu thức chính quy cho đối số để giảm bớt các lỗi truy vấn và tăng độ an toàn cho một route.
Ví dụ mình định nghĩa một route là /users/:user
với đối số :user mong muốn là một username. Lúc này mình biết rõ là username của ứng dụng có độ dài từ 8 đến 30 kí tự chỉ bao gồm chữ cái tiếng anh hoa, thường , chữ số từ 0 đến 9 và ba ký tự đặc biệt là -, . và _.
Như vậy mình có thể áp dụng một biểu thức chính quy cho đối số này
:user(^[A-Za-z0-9\.\-_]{8,30}+$) ==> Lúc này nếu bạn nhập vào một đường dẫn có đối số :user nhỏ hơn 8 hoặc lớn 30 ký tự thì route trên sẽ không nhận, hoặc chứa ký tự khác dấu ., _ và - , thì route cũng không nhận.
Từ đó hạn chế được việc query một username bị sau quy tắc và lại an toàn tránh tấn công SQL injection.
2) **router.param(name, callback)** là một kỹ thuật cho phép gán các hàm xử lý cho một đối số cụ thể trên route.
Ví dụ như trong bài thực hành mình có mọi một route param là :author , cái này thực chất là username hoặc author ID.
```javascript
router.route('/:author([a-zA-Z0-9.\-_]{8,30})')
.get(AuthorCtrl.renderAuthorPage);
```
Thì mình sẽ áp dụng kỹ thuật trên để gán một hàm xử lý vào param này.
```javascript
// Resolve route params
router.param('author', AuthorCtrl.findOne);
```
Nghĩa là cữ mỗi khi gặp route có param :author thì sẽ gọi hàm AuthorCtrl.findOne
Hàm đó được định nghĩa như sau
```javascript
/**
* @name findAuthorByUsernameOrId
* @description
* Populate author data to HTTP request.
*
* @param {object} req HTTP request.
* @param {object} res HTTP response.
* @param {object} next Next middleware
* @param {object} author Author id or username.
*/
function findAuthorByUsernameOrId(req, res, next, author) {
AuthorService.findByUsernameOrId(author)
.then(_author => {
req.author = _author;
return next();
})
.catch(err => next(err));
}
```
Ta thấy răng nó sẽ truy vấn vào Model, với tham số là username hoặc Id nhận được, và chờ kết quả trả về. Nếu có kết quả trả về thì sẽ gắn author vào đối tượng HTTP request req rồi chuyển đến middleware tiếp theo.
Từ đó ở một midleware tiếp theo như là renderAuthorPage chẳng hạn, bạn không cần phải gọi truy vấn vào cơ sở dữ liệu để lấy author nữa, mà chỉ đơn giản như sau.
```javascript
/**
* @name renderAuthorPage
* @description
* Render HTTP page for view author information.
*
* @param {object} req HTTP request
* @param {object} req.author Author selected.
* @param {object} res HTTP response
*/
function renderAuthorPage(req, res) {
res.render('author/view', {
author : req.author
});
}
```
để ý là render lên trang author/view với dữ liệu truyền vào chính là req.author.
**Ứng dụng**
Cách tiếp cận như trên rất là tốt, thay vì ở mỗi controller có đối số :author bạn phải gọi lại service để lấy author thì như trên chỉ cần viết một lần là đủ, rất tiện và tránh trùng lặp code.
## 3.5 Route handlers
Đơn giản là một hoặc nhiều function sẽ được gọi khi một route trùng khớp để đáp ứng một yêu cầu nào đó. Lưu ý các handler sẽ được gọi đúng theo thứ tự truyền vào. Ví dụ
app.get('/user', [a, b]);
thì a sẽ gọi trước b. Chú ý là để b được gọi thì trong a phải gọi hàm next(). Ví dụ
```javascript
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
var cb2 = function (req, res) {
res.send('Hello from C!')
}
app.get('/c', [cb0, cb1, cb2]);
```
**Ứng dụng**
Thường thì mình áp dụng kỹ thuật trên để tạo ra các polixy để bảo đảm thẩm quyền người dùng trên hành động nào đó, ví dụ mình nói là muốn xem thông tin thành viên thì phải đăng nhập trước. Khi đó mình có thể định nghĩa một route như sau.
```javascript
function isLogged(req, res, next) {
if( Đã login ) {
return next();
}
return res.status(403).redirect('/login');
}
function renderProfilePage(req, res, next) {
// Do render profile page...
}
app.get('/users/:user', [isLogged, renderProfilePage]);
```
Hoặc thực hiện việc logging thông tin các request để lưu trữ xem ai làm gì, ví dụ:
```javascript
function isLogged(req, res, next) {
if( Đã login ) {
return next();
}
return res.status(403).redirect('/login');
}
function renderProfilePage(req, res, next) {
// Do render profile page...
}
function logRequest(req, res, next) {
// Do logging IP, Header request
next();
}
app.get('/users/:user', [isLogged, logRequest, renderProfilePage]);
```
Có một kỹ thuật khác nữa hay được áp dụng đó là kiểm tra tần suất gọi request của một địa chỉ IP nào đó để tránh các cuộc tấn công DDOS.
Và rất nhiều thứ khác có thể áp dụng thêm, các bạn có thể linh động nghĩ ra.
## 3.6 Response methods
Sau việc tiếp nhận và xử lý, thì việc tiếp theo đó là đáp ứng (Response). Trong express định nghĩa sẵn một số phương thức hỗ trợ cho bạn như là:
Tên phương thức | Ý nghĩa
-------------------|------------------------------------------
res.json() | Trả về một dữ liệu dạng JSON
res.redirect() | Chuyển hướng đến đường dẫn nào đó
res.render() | Trả về một view template
res.send() | gửi dữ liệu dạng text
Ở trên là những phương thức hay dùng nhất.
### 3.7 app.route()
Đây là một cách định nghĩa route rõ ràng hơn, mới được hỗ trợ trong các phiên bản mới. Ví dụ thay vì bạn định nghĩa như sau.
```javascript
function doGet(req, res, next) {
// something ...
}
function doPost(req, res, next) {
// something ...
}
function doPut(req, res, next) {
// something ...
}
app.get('/users/:user', doGet);
app.post('/users/:user', doPost);
app.put('/users/:user', doPut);
```
thì áp dụng app.route chúng ta có thể làm ngắn gọn như sau
```javascript
function doGet(req, res, next) {
// something ...
}
function doPost(req, res, next) {
// something ...
}
function doPut(req, res, next) {
// something ...
}
app.route('/users/:user')
.get(doGet)
.post(doPost)
.put(doPut);
```
mình rất thích dùng cách app.route vì nó gọn và dễ nhìn hơn rất nhiều.
### 3.8 express.Router
Đây là một điều thú vị được cập nhận trong phiên bản mới của Express, giúp chúng ta có thể module hóa công việc định tuyến thành cái module nhỏ có thể sử dụng lại.
Ví dụ mình định nghĩa một module route có khả năng trả về thời gian hiện tại khi truy cập /time như dưới đây . Mình để trong file là **time.server.routes.js**
```javascript
var express = require('express')
var router = express.Router()
router.get('/time', function (req, res) {
res.send(Date.now());
})
module.exports = router
```
Thì sau đó tại phần server.js mình sẽ gọi route đó ra và gắn vào một đường dẫn là /helper như sau .
```javascript
var timeRoutes = require('./routes/time.server.routes');
// ...
app.use('/helpers', timeRoutes);
```
Như trên ta có thể truy cập để lấy thời gian ở route là `GET /helper/time` . Rất tiện đúng không nào.
Không chỉ như thế, các bạn có thể tận dụng lại nó trên một đường dẫn khác như sau.
```javascript
var timeRoutes = require('./routes/time.server.routes');
// ...
app.use('/helpers', timeRoutes);
app.use('/app', timeRoutes);
```
Vậy là ngoài cách truy cập vào `/helpers` các bạn có có thể try cập vào bằng đường dẫn `/app/time`. Rất là tiện đúng không nào, với tính năng này các bạn có thể linh hoạt sử dụng lại các module routes của mình dễ dàng và tiện dụng, tránh phải định nghĩa lại gây trùng lặp mã không đáng có.
Và đến đây là chúng ta đã hoàn thành phần lý thuyết, kế đến là phần thực hành của bài học.
## 4. Thực hành
Bài thực hành,rất sát với thực tế nên thật sự là rất khó, các bạn để làm được bài thực hành này cần phải có kiến thức của bài học trước.
Tuy nhiên dưới đây mình sẽ điểm sơ qua các phần nội dung chính của bài thực hành, còn phân tích chi tiết về bài thực hành này mình sẽ viết ở một bài viết thực hành khác.
Toàn bộ source code được để ở github theo link sau. [Socis-blog-v2 Github](https://github.com/nghuuquyen/sociss-class-nodejs/tree/master/src/sociss-blog-v2)
### 4.2 Cơ bản về mô hình MVC
Mình sẽ có bài học khác phân tích sâu hơn vào MVC, tuy nhiên ở bài học này mình sẽ giới thiệu sơ qua và áp dụng nó vào bài thực hành để các bạn dần dần nắm bắt được một kiến trúc ứng dụng tốt cho các website Node.js nói riêng và trên cả những công nghệ khác nữa.
Thì trong MVC, nguyên tắc chung là chia ứng dụng thành ba phần riêng biệt là Model, View và Controller.
Trong đó:
**Model** bao gồm việc tương tác nhập xuất dữ liệu và các logic nghiệp vụ trên dữ liệu.
**View** là thành phần giao diện tương tác với một cái gì đó, ở trong website thì có thể hiểu là người dùng còn view chính là trang HTML + CSS.
**Controller** Là thành phần điều khiển, có trách nhiệm là thành phần **trung gian** để **điều hướng** , **truyền nhận dữ liệu** từ Model qua lại với View và thực hiện các **logic nghiệm vụ trên View** để tương tác với người dùng.
Mình nhấn mạnh lần nữa trong mô hình **MVC chuẩn**, Controller chỉ có trách nhiệm **điều hướng** và **truyền nhận dữ liệu** và thực hiện **logic nghiệp vụ trên View**.
trong đó cụ thể hơn
**Điều hướng** : Các bạn sử dụng controller để điều hướng qua lại giữa các trang khác nhau
**Truyền nhận dữ liệu**: Các controller sẽ tiếp nhận tác nhân **thông qua view gửi lên** , tại đây controller có thể thực hiện một số thao tác kiểm tra dữ liệu và sau đó gửi dữ liệu liệu cho các module Service để xử lý và nhận dữ liệu trả về rồi gửi ngược lại cho View.
Thường thì trong một ứng dụng MVC, controller không trực tiếp tương tác với model mà là thông qua Service, trong đó bên trong Service lại gọi đến Model và thực hiện mỗi chuỗi nghiệp vụ cần thiết nào đó rồi mới gửi dữ liệu về. Mình ví dụ
Bạn gọi một Service tạm gọi là PostService để tạo một bài viết cho một ngươi dùng dùng A có nội dung bài viết là Post B.
Thì khi ấy PostService sẽ thực hiện một chuỗi nghiệp vụ sau
1) Kiểm tra người dùng A có tồn tại không
2) Kiểm tra người dùng A có được phép đăng bài không
3) Kiểm tra bài viết B có hợp lệ không
4) Tiến hành liên kết bài viết B với người dùng A và nhập vào cơ sở dữ liệu
5) Tiến hành lưu trữ Logging hệ thống
6) Tiến hành tạo thông báo hồi đáp
......
Như ví dụ trên thì các bạn thấy rằng một Service có thể tương tác với một hoặc mỗi chuỗi các nghiệp vụ các Model khác nhau, chứ không chỉ một Service là đi theo một Model cụ thể nào.
>Trong bài thực hành mình có áp dụng cả Service trong đó, tuy nhiên vì nó đơn giản và không chứa nghiệp vụ nên có thể các bạn không nhìn ra lợi ích của nó, tuy nhiên đó là một mô hình đáng để làm theo, và sẽ có ích trong các bài học sau. Khi mà mình bắt đầu đi sâu vào các rằng buộc trên nghiệp vụ.
### 4.3 Cấu trúc thư mục bài thực hành
Bài thực hành có cấu trúc thư mục như sau
```markup
.
├── app
│ ├── controllers
│ │ ├── author.server.controller.js
│ │ ├── core.server.controller.js
│ │ └── index.js
│ ├── errors
│ │ ├── BaseError.js
│ │ ├── InvalidParamError.js
│ │ └── NotFoundError.js
│ ├── models
│ │ ├── author.server.model.js
│ │ ├── index.js
│ │ └── post.server.model.js
│ ├── routes
│ │ ├── author.server.routes.js
│ │ ├── core.server.routes.js
│ │ └── index.js
│ ├── services
│ │ ├── author.server.service.js
│ │ ├── index.js
│ │ └── post.server.service.js
│ └── views
│ ├── about.server.view.html
│ ├── author
│ │ ├── posts.server.view.html
│ │ └── view.server.view.html
│ ├── error.server.view.html
│ └── home.server.view.html
├── config
│ ├── env
│ └── lib
├── public
│ ├── css
│ ├── images
│ └── js
├── README.md
└── server.js
```
Trong đó, gần giống bài học trước, chỉ có thêm thư mục **errors** mình dùng để lưu các đối tượng Error để giúp cho việc xử lý lỗi trong ứng dụng trong sáng và rõ ràng hơn.
### 4.4 Định nghĩa phần Route cho Author
Trong file **/app/routes/author.server.routes.js** . Mình dùng kỹ thuật express.Router để tạo một module routes như sau.
```javascript
/**
* @author <NAME>
* @module routes
* @name author.server.routes
*/
"user strict";
let router = require('express').Router();
let AuthorCtrl = require('../controllers').Author;
// Resolve route params
router.param('author', AuthorCtrl.findOne);
// Public routes
router.route('/:author([a-zA-Z0-9.\-_]{8,30})')
.get(AuthorCtrl.renderAuthorPage);
router.route('/:author([a-zA-Z0-9.\-_]{8,30})/posts')
.get(AuthorCtrl.renderAuthorPostsPage);
module.exports = router;
```
Sau đó tại **/app/routes/index.js**. Mình gọi nó ra và gắn vào đường dẫn /author như sau
```javascript
/**
* @author <NAME>
* @module routes
* @description
* Active all routes of application and simple handle error.
*/
"user strict";
let router = require('express').Router();
// Application routes
router.use('/', require('./core.server.routes'));
router.use('/author', require('./author.server.routes'));
module.exports = router;
```
Và cuối cùng tại file **server.js** mình gắn toàn bộ application routes vào HTTP server như sau.
```javascript
"use strict";
const express = require('express');
const app = express();
const port = 3000;
let hbs = require('express-hbs');
// Do Registration routes.
app.use(require('./app/routes'));
.....
```
Như vậy là xong phần đăng ký routes cho ứng dụng.
Tiếp đến mình sẽ xét đến phần Controller.
### 4.5 Định nghĩa phần Contrller cho Author
Tại file **/app/controllers/author.server.controller.js** các bạn gõ vào đoạn code như sau.
```javascript
/**
* @author <NAME>
* @module controller
* @name author.server.controller
*/
"use strict";
let Services = require('../services');
let AuthorService = Services.Author;
let PostService = Services.Post;
module.exports = {
findOne : findAuthorByUsernameOrId,
renderAuthorPage : renderAuthorPage,
renderAuthorPostsPage : renderAuthorPostsPage
};
/**
* @name renderAuthorPage
* @description
* Render HTTP page for view author information.
*
* @param {object} req HTTP request
* @param {object} req.author Author selected.
* @param {object} res HTTP response
*/
function renderAuthorPage(req, res) {
res.render('author/view', {
author : req.author
});
}
/**
* @name renderAuthorPostsPage
* @description
* Render HTTP page list all posts of selected author.
*
* @param {object} req HTTP request
* @param {object} req.author Author selected.
* @param {object} res HTTP response
* @param {object} next Next middleware
*/
function renderAuthorPostsPage(req, res, next) {
PostService.findPostsByAuthor(req.author.id).then(_posts => {
res.render('author/posts', {
author : req.author,
posts : _posts
});
})
.catch(err => next(err));
}
/**
* @name findAuthorByUsernameOrId
* @description
* Populate author data to HTTP request.
*
* @param {object} req HTTP request.
* @param {object} res HTTP response.
* @param {object} next Next middleware
* @param {object} author Author id or username.
*/
function findAuthorByUsernameOrId(req, res, next, author) {
AuthorService.findByUsernameOrId(author)
.then(_author => {
req.author = _author;
return next();
})
.catch(err => next(err));
}
```
Để ý một phần code nhỏ trong đó
```javascript
/**
* @name renderAuthorPostsPage
* @description
* Render HTTP page list all posts of selected author.
*
* @param {object} req HTTP request
* @param {object} req.author Author selected.
* @param {object} res HTTP response
* @param {object} next Next middleware
*/
function renderAuthorPostsPage(req, res, next) {
PostService.findPostsByAuthor(req.author.id).then(_posts => {
res.render('author/posts', {
author : req.author,
posts : _posts
});
})
.catch(err => next(err));
}
```
Ở đây mình sẽ gọi PostService, với dữ liệu vào là author ID để lấy ra toàn bộ posts của tác giả đấy. Sau khi lấy được xong thì mình sẽ gửi trả ngược dữ liệu về. Và Controller nhận dữ llệu ấy và Render lên trang View author.posts phù hợp.
### 4.6 Định nghĩa phần Service cho Author
Trong file **/app/services/author.server.service.js** bạn sẽ thấy đoạn mã sau.
```javascript
/**
* @module services
* @author <NAME>
* @name author.server.service
*/
"use strict";
let Author = require('../models').Author;
module.exports = {
findByUsernameOrId : findByUsernameOrId,
getAllAuthors : getAllAuthors
};
/**
* @name findByUsernameOrId
* @description
* Find one author by username or id.
*
* @param {string} _param Username or Id of author.
* @return {promise.<object>} Author object.
*/
function findByUsernameOrId(_param) {
// TODO: More business logic code here.
return Author.findOne(_param);
}
/**
* @name getAllAuthors
* @description
* Get all authors in database
*
* @return {promise.<array>} Authors.
*/
function getAllAuthors() {
// TODO: More business logic code here.
return Author.getAll();
}
```
Nó chủ yếu là gọi đến Author Model để lấy và truy xuất dữ liệu.
### 4.6 Định nghĩa phần Model cho Author
Cuối cùng là phần
```javascript
/**
* @author <NAME>
* @module models
* @name author.server.model
*/
"user strict";
let NotFoundError = require('../errors/NotFoundError');
let authors = [
{
id : '1111',
fullName : 'Author A',
username : 'author_a'
},
{
id : '1112',
fullName : 'Author B',
username : 'author_b'
}
];
module.exports = {
findOne : findOne,
getAll : getAll
};
/**
* @name getAll
* @description
* Get all authors.
*
* @return {promise.<array>} List of authors.
*/
function getAll() {
return new Promise((resolve, reject) => {
resolve(authors);
});
}
/**
* @name findOne
* @description
* Find one author by username or id.
*
* @param {string} _id username or id
* @return {promose.<object>} Author object.
*/
function findOne(_id) {
return new Promise(( resolve, reject ) => {
for(i in authors) {
if(authors[i].id === _id || authors[i].username === _id) {
return resolve(authors[i]);
}
}
reject(new NotFoundError(`Not found author with id or user name equal ${_id}`));
});
}
```
trong này mình không sử dụng cơ sở dữ liệu , nên lưu trong một biến global. Kế đó mình đơn giản là định nghĩa ra một vài method tương tác với biến dữ liệu Global đó để trả dữ liệu về.
**Lưu ý**
Tất cả các hàm mình đều dùng Promise vì trong thực tế khi sử dụng cơ sở dữ liệu, mọi thứ đều có độ trễ. Nên dù chỉ là một ví dụ nhỏ trong bài thực hành, mình đều muốn nó gắn liền với hiện thực.
### 4.7 Xử lý lỗi trên route
Các bạn dễ ý trong file **/app/routes/index.js** . Mình có thêm một đoạn code sau. Đoạn code này là áp dụng tính chất của **middleware** trong Express.js để thực hiện. Trong đó middleware xử lý lỗi sẽ nằm ở cuối cùng trong một chuỗi các middleware.
Vì ý tưởng chủ đạo là dựa vào nguyên tắc nếu tại một middleware xử lý nào đó mà không có lỗi gì xảy ra thì sẽ ngắt luôn tại vị trí đó, còn nếu có lỗi thì sẽ ném lên middleware tiếp theo. Và như vậy sẽ định nghĩa một middleware cuối cùng bắt tất cả lỗi đó.
```javascript
// catch 404 and forward to error handler
router.use((req, res, next) => {
const err = new NotFoundError('Page not found');
return next(err);
});
// Error handle
router.use(function(err, req, res, next) {
const _status = err.status || 500;
res.status(_status);
res.render('error', {
message: err.message,
status : _status
});
});
```
## 5. Kết luận bài học
Qua bài học này, mình đã giới thiệu cho tất cả các bạn các kỹ thuật cơ bản và cả nâng cao của Routing. Kèm theo đó là một bài thực hành rất khó và bám sát với thực tế lập trình.
Mình chắc chắn sẽ có một bài viết hướng dẫn thực hành cho bài viết này. Tuy nhiên mình cũng muốn các bạn nắm rõ các kiến thức sau.
1) Hiểu rõ về Routing và các định nghĩa của nó.
2) Biết được Express cung cấp cho ta những tính năng gì để hỗ trợ cho việc Routing.
3) Nắm được ý tưởng về mô hình MVC.
4) Thấy được kiến trúc thực tế của một trang website xây dựng theo mô hình MVC.
## 6 Bài tập về nhà
1) Các bạn cố gắng tải mã nguồn bài học trên về tìm hiểu và chạy thử. Cách chạy vẫn giống như mọi khi `node server`.
2) Thử làm một số route đơn giản như những bài học trước để trả về nội dung cho trang view, áp dụng kỹ thuật express.Router để module hóa routes.
Mã nguồn của bài học mình để ở Github theo link sau [Socis-blog-v2 Github](https://github.com/nghuuquyen/sociss-class-nodejs/tree/master/src/sociss-blog-v2)
# Tác giả
**Name:** <NAME> ( <NAME> )
**Email:** <EMAIL>
**Website:** [Sociss Class - Online Education Center](https://sociss.edu.vn/)
**Profile Page:** [<NAME> - Profile Page ](https://sociss.edu.vn/users/nghuuquyen)
<file_sep>console.log('Should equals true : ', isMorning('morning'));
function isMorning(time) {
if(!time) return false;
if(time === 'morning') {
return true;
}
else {
return false;
}
}
<file_sep>Chào các bạn trong bài học này, mình muốn giới thiệu đến các bạn công nghệ Git. Git là một công cụ giúp quản lý các phiên bản của mã nguồn, hỗ trợ cho làm việc nhóm một cách hiệu quả.
Trong bài học này, mình sẽ giới thiệu và giải thích tất cả các khái niệm trung tâm và quan trọng nhất khi làm việc với Git. Nắm chắc những khái niệm này thì việc thực hành và đi sâu vào các câu lệnh về Git sẽ vô cùng dễ dàng.
Nào chúng ta cùng đi vào bài học.
# 1. Tại sao cần Git ?
Trong việc phát triển phần mềm chúng ta thường thao tác trên rất nhiều tệp tin khác nhau. Với mỗi tệp tin chúng ta sẽ tương tác chỉnh sửa rất nhiều lần. Câu hỏi đặt ra là làm thế nào để có thể phục hồi trạng thái của tệp tin đó trở lại trạng thái trước đó nếu lỡ chúng ta gây ra lỗi.
Thì cách đơn giản nhất đó chính là sao lưu cẩn thận nó sau mỗi lần làm việc, theo một cách đặt tên thống nhất ví dụ.
```markup
(18-09-2017)-core.server.controller.js
(19-09-2017)-core.server.controller.js
(20-09-2017)-core.server.controller.js
```
Cách trên cũng là một giải phát có thể áp dụng được tốt nếu chúng ta làm việc một mình, tuy nhiên để dễ quản lý hơn trước đây mình còn làm tên một file text để viết vào đó dòng mô tả xem ứng với phiên bản file đó thì mình làm công việc gì. Ví dụ về file text mình từng dùng
```markup
# 1. (18-09-2017)-core.server.controller.js
Complete view feature.
# 2. (19-09-2017)-core.server.controller.js
Add new feature show contact page.
# 3.(20-09-2017)-core.server.controller.js
Add new feature show about page.
```
Đó là cách mình quản lý source code của mình vào năm mình học cấp 3. Lúc ấy mình chưa biết GIT là gì, tuy nhiên khi đến lúc làm việc nhóm thì sẽ vô cùng phức tạo vì để chuyển giao mã nguồn cho bạn của mình, thì chỉ có cách nén lại gửi qua email. Việc nén gửi đi tạo ra vô số bản sao chép gây khó kiểm soát. Kế đến còn có trường hợp cả hai cùng sửa cùng một file nếu copy đè lên sẽ gây mất code của người kia, dần dần mọi việc trở nên hỗn loạn. Và cả nhóm phải đành code trên một máy hoặc share một thư mục chung qua mạng, vất vả vô cùng.
Sau này biết đến Git mọi thứ đều thay đổi, việc làm việc nhóm trở nên đơn giản và hiệu quả hơn. Ngay cả công việc code cá nhân cũng trở nên dễ dàng, mình không còn phải sao lưu từng tệp tin nữa.
# 2. Git là gì ?
Git là một trong những Hệ thống Quản lý Phiên bản Phân tán, vốn được phát triển nhằm quản lý mã nguồn (source code) của Linux.
Trên Git, ta có thể lưu trạng thái của file dưới dạng lịch sử cập nhật. Vì thế, có thể đưa file đã chỉnh sửa về trạng thái cũ hay có thể biết được file đã được chỉnh sửa chỗ nào do ai đã chỉnh sửa.
Thêm nữa, khi định ghi đè (overwrite) lên file mới nhất đã chỉnh sửa của người khác bằng file đã chỉnh sửa dựa trên file cũ, thì khi upload lên server sẽ hiện ra cảnh cáo. Vì thế, sẽ không xảy ra lỗi khi ghi đè lên nội dung chỉnh sửa của người khác mà không hề hay biết.
Git sử dụng mô hình phân tán, mỗi thành viên trong team sẽ có một repository ở máy của riêng mình. Điều đó có nghĩa là nếu có 3 người A,B,C cùng làm việc trong một project. Thì bản thân repo trên máy của người A, người B, và người C có thể kết nối được với nhau.
Trong mô hình Git sẽ luôn có một server lưu trữ chính để cả team cùng kết nối thông qua đó (Có thể là Github, bitbucket, ...). Ngoài ra mỗi người trong team đều có thể kết nối đến máy tính của nhau thông qua SSH.
# 3. Repository là gì ?
Repository hay được gọi tắt là Repo, đơn giản là nơi chứa tất cả những thông tin cần thiết để quản lý các sửa đổi và lịch sử của toàn bộ project. Tất cả dữ liệu của Repo đều được chứa trong thư mục bạn đang làm việc dưới dạng folder ẩn có tên là .git
Nên bạn phải chú ý không được xóa thư mục này đi, nếu không sẽ mất thông tin quan trọng.
# 4. Remote repository và local repository
Repository của Git được phân thành 2 loại là **remote repository** và **local repository**.
+ **Remote repository**: Là repository dùng để chia sẽ giữa nhiều người và bố trí trên server chuyên dụng.
+ **Local repository**: Là repository ở trên máy tính của chính bản thân mình, dành cho một người dùng sử dụng.
Thường thì trong quá trình làm việc chúng ta sẽ làm việc trên local repo, tức là lưu trữ trên máy của mình. Khi muốn chia sẽ nó đến người dùng khác khi đã hoàn thành thì sẽ đẩy code (Push) lên Remote repo.
# 5. Git Remote
Để kết nối được với một repo khác người ta sử dụng một khái niệm gọi là remote tạm hiểu là
kết nối từ xa đến một remote git server. Là một máy tính trên đó cài phần mềm git
server để quản lý source code. Tai đây chúng ta có thể thực hiện các thao tác như
đẩy (push), kéo (pull) , nhân bản (clone) . Tuy nhiên thường thì không phải máy tính
ai cũng cài đặt git server và đảm bảo hoạt động ổn định 24/24, nên thường là người ta
sẽ sử dụng một dịch vụ Cloud Git Server nào đó để làm remote server. Hai nhà cung cấp
ổn định nhất hiện tại là github.com và bitbucket.org.
Mọi người sẽ có tài khoản của các nhà cung cấp trên, kết nối đến đó và đẩy mã nguồn
của mình lên đó để các thành viên khác lên đó lấy về. Dựa vào đó mà mọi thành viên
có thể chia sẽ mã nguồn với nhau dễ dàng mọi thứ sẽ được đồng bộ trên remote server.
Vì vậy, trước khi sử dụng git thì bạn nên đăng kí một tài khoản trên github.com hoặc bitbucket.org.
# 6. Commit

**Commit** là thao tác để **ghi lại** lịch sử việc thêm, thay đổi file hay thư mục vào repository.
Khi thực hiện commit, trong repository sẽ tạo ra commit (hoặc revision) đã ghi lại sự khác biệt từ trạng thái đã commit lần trước với trạng thái hiện tại.
Commit này đang được chứa tại repository, các commit nối tiếp với nhau theo thứ tự thời gian. Bằng việc lần theo commit thì có thể biết được lịch sử thay đổi trong quá khứ.
# 7. Nhánh (Branch)

Nhánh có thể hiểu như là một không gian làm việc (workspace), Ví dụ khi bạn muốn
tạo một tính năng A mới bạn sẽ tạo ra một nhánh mới để làm tính năng A. Đồng thời
trong lúc bạn làm tính năng A thì bạn cũng có thể tạo ra một nhánh mới để sửa lỗi
cho dự án của mình. Hai không gian làm việc này hoàn toàn không động đến nhau, nên
dù tính năng A đã làm xong hay chưa đều không ảnh hưởng đến các nhánh (không gian làm việc) khác.
Trong một project sẽ luôn có một nhánh chính (mặc định) gọi là **master**. Tính năng được tạo
ra trong các nhánh phụ sẽ được hợp nhất lại vào master khi đã làm xong, hành động này
gọi là **merge**
# 8. Merge (Trộn)
Merge là hành động khi bạn muốn nhập mã nguồn từ một nhánh khác vào nhánh hiện tại.
Ví dụ từ nhánh master bạn tạo ra một nhánh là **feature-seo** đây là nhanh phát triển
tính năng cho việc SEO onpage. Sau khi bạn hoàn tất tính năng này thì bạn sẽ phải merge
nó vào lại master, vì master là nhánh chính, hiểu là nơi chứa mã nguồn với đầy đủ tính năng
của cả project. Việc merge sẽ mang tính năng seo đang ở nhánh **feature-seo** vào nhánh **master**
# 9. Working tree và Index (hoặc staging area)

Trên Git, những thư mục được đặt trong sự quản lý của Git, để mọi người thực hiện công việc trên đó, được gọi là **working tree**.
Giữa repository và working tree tồn tại một nơi gọi là index hay staging area . staging area là nơi để chuẩn bị cho việc commit vào repository.
# 10. Tracked và Untracked
Trong git có hai loại trạng thái chính đó là Tracked và Untracked. Nếu bạn muốn commit một tập tin đó, bạn sẽ cần phải đưa tập tin đó vào trạng thái tracked bằng lệnh **git add**.
1) **Tracked** – Là tập tin đã được đánh dấu theo dõi trong Git để bạn làm việc với nó. Và trạng thái Tracked nó sẽ có thêm các trạng thái phụ khác là Unmodified (chưa chỉnh sửa gì), Modified (đã chỉnh sửa) và Staged (đã sẵn sàng để commit).
2) **Untracked** – Là tập tin còn lại mà bạn sẽ không muốn làm việc với nó trong Git.
Nhưng nếu tập tin đó đã được Tracked nhưng đang rơi vào trạng thái (Modified) thì nó vẫn sẽ không thể commit được mà bạn phải đưa nó về Staged cũng bằng lệnh git add
## Untracked
Nếu bạn tạo ra hoặc thêm vào một tập tin mới vào trong thư mục làm việc của bạn thì nó sẽ ở trạng thái Untracked. muốn cho nó trở thành tracked thì phải dùng lệnh
git add. Nếu tệp tin đó mới hoàn toàn thì nó sẽ rơi vào trạng thái **staged** và
bạn có thể commit file đó.
## Tracked
Một khi một tập tin đã được đưa về Tracked thì nó sẽ có thể thay đổi giữa 3 trạng thái khác nhau là Modified, Unmodified và Staged.
1) **Unmodified** : File đươc Git quản lý nhưng không có thay đổi gì
2) **Modified** :File được Git quản lý nhưng đang bị thay đổi, cần dùng lệnh git add để đưa về trạng thái staged
3) **staged** : File được git quản lý và sẵn sàng cho việc commit.
**Chú ý** : Một file đã ở trạng thái Staged mà bạn lại tiếp tục sửa thì nó
sẽ quay về trạng thái modified, lúc này lại cần git add để xác nhận thay đổi,
và đưa file quay về trạng thái staged.
# 11. tệp tin .gitignore
.gitignore Là một file cấu hình của git. **Tại khai báo tất cả các file hoặc thư mục mà ta sẽ untracked**. Tức là khai báo những file mà ta không muốn git quản lý, những file này sẽ không bao giờ được commit.
Ứng dụng của file này là để loại bỏ các tệp tin thừa do hệ điều hành, công cụ làm việc sinh ra trong lúc làm việc, những file này không có giá trị nên không bao giờ
cần phải quản lý bởi Git cả.
**Chú ý** : Thường khi làm việc với một công nghệ cụ thể nào đó thì đề có một
file .gitignore mẫu sẵn, bạn có thể lên mạng tải về để sử dụng, trong quá trình
sử dụng bạn có thể thêm vào file .gitignore các file đặc biệt mà bạn muốn bỏ ra khỏi Git tương ứng với công việc của bạn.
**Ví dụ** Với ngôn ngữ Java, khi mã nguồn được biên dịch, thì file .class sẽ được sinh ra, nhưng file này lại không cần phải quản lý bởi Git do nó sinh ra từ file
.java. Nên ta sẽ loại bỏ nó bằng cách khai báo trong .gitignore là
```markup
*.class
```
Ở trên nghĩa là bỏ hoàn toàn các file có phần mở rộng là .class.
# 12. Add, Pull, Push, Clone
**add** là thao tác đẩy một tệp tin từ working directory vào staging area để chuẩn bị cho việc commit.
**pull** là thao tác lấy mã nguồn từ một hoặc nhiều nhánh cụ thể nào đó ở
remote server nào đó về local repository trên máy tính của bạn
**push** là thao tác đẩy mã nguồn hiện tại đã được commit của bạn lên remote server.
**clone** là thao tác tải mã nguồn từ một remote server về máy tính,chỉ tải
về máy local repository nhánh master
# 13. Conflict (Xung đột)
Giả sử ta có file A. Và trong team gồm hai anh chị làm việc ở hai nhánh khác nhau.
Ví dụ tại dòng số 10 đến 20 của file A. Anh lập trình viên viết vào đó hàm cộng, nhưng chị lập trình viên khác trên một nhánh khác lại viết vào đó hàm trừ.Lúc này khi anh lập trình viên
merge code từ nhánh của chị kia về thì Git bó tay không biết nên theo ai, nên sẽ báo Conflict (xung đột).
Vậy Conflic là trường hợp có 2 sự thay đổi trong cùng một hay nhiều dòng code trên một file mà Git không thể tự quyết định cách giải quyết cho "đúng" khi merge mã nguồn từ một nhánh khác về . Đúng ở đây có nghĩa là đúng "ý đồ của lập trình viên".
Để giải quyết mâu thuẫn bạn phải dùng “tay" hay ám chỉ tự xử, để sữa các xung đột này. Bạn đơn giản chỉ việc nhìn vào file bị conflict cùng với các cộng sự của mình để tự quyết định dòng code nào giữ lại, dòng nào xóa bỏ hay phối hợp với nhau.
Như ví dụ trên, khi xảy ra xung đột, lúc này để giải quyết hai anh chị lập trình viên phải ngồi với nhau để sắp xếp lại hai function đúng vị trí trong file A. Và đó gọi là giải quyết xung đột.
# Tác giả
**Name:** <NAME> ( <NAME> )
**Email:** <EMAIL>
**Website:** [Sociss Class - Online Education Center](https://sociss.edu.vn/)
**Profile Page:** [<NAME> - Profile Page ](https://sociss.edu.vn/users/nghuuquyen)
<file_sep>
# Những kinh nghiệm đúc kết được sau một thời gian lập trình Node JS .
Sau một thời gian dài làm việc với Node JS nói riêng và cảm nhận về việc phát triển phân mềm nói chung mình rút ra được một số kinh nghiệm sau.
## I. Cách để có thể học và làm quen với việc sử dụng Node JS.
Để học được Node JS thì đầu tiên các bạn nên lên Youtube xem video trước, để biết nó ra sao và làm thế nào cài đặt, làm thế nào có thể chạy thử một ứng dụng “Hello World”.
Thứ hai, các bạn có thể lên các trang như [W3Schools Online Web Tutorials](https://www.w3schools.com/) hay [TutorialsPoint](https://www.tutorialspoint.com/) để học các kiến thức bắt đầu như cấu trúc câu lệnh, từ khóa, các hàm hay thư viện thường dùng.
Sau một thời gian mày mò khởi động, mình tin rằng các bạn sẽ thấy ứng dụng thấy rõ nhất của Node JS là xây dựng một trang web, lúc này không cần nghĩ nhiều các bạn hay thử mày mò làm thử một trang web nhỏ cho mình (Nhớ là giữ nó thật nhỏ). Sau khi tạo ra được một sản phẩm nho nhỏ cho mình như một web todo hay như cái mình làm đầu tiên chính là một mini blog để mình viết bài chẳng hạn. Đến khi có một sản phẩm nhỏ cho riêng mình thì chính lúc đó các ban đã có một thứ vô cùng quan trọng đó là.
Biết mình đang học cái gì và dùng làm cái gì. Đây là một câu trả lời mà nhiều khi có những bạn học cả năm trời cũng không biết cái mình học là gì và mình đang làm cái gì.
Lời khuyên: Node JS thì không phụ thuộc vào IDE, các bạn hãy cài Atom, Visual Studio Code hay Sublime Text để code, việc dùng Text Editor để code và chạy chương trình thông qua Terminal là kỹ năng bắt đầu tốt và giúp các bạn tự tin hơn về sau.
## II. Bắt đầu bước vào con đường chuyên nghiệp hơn .
Một sự thật là các bạn sau khi hoàn thành bước 1 ở trên thì sẽ bắt đầu mất định hướng, không biết đi đâu và làm gì tiếp theo. Vì một trong những nguyên nhân dưới đây.
1. Không biết ngoài công ty người ta làm dự án với công nghệ này ra sao ?
2. Mình học như vậy là đã xin được việc làm chưa, cần học thêm gì nữa ?
3. Giờ muốn làm cho mình một sản phẩm thì đã được chưa nhỉ ?
4. Tự cảm thấy có gì đó chưa ổn làm khi nhìn lại Code, bạn tốn quá nhiều thời gian và có một chút gì đó thiếu tự tin khi muốn trình bày mã của mình ra cho một ai đó ?
Và tất nhiên là còn nhiều điều nữa, nhưng những điều trên chính là những gì chính bản thân mình gặp trong khoảng 3 năm trước đây.
Và các để không lạc lối ở giai đoạn này thì các bạn phải nhìn nhận một số điều sau đây.
a) Ở công ty người ta không làm việc một mình, họ làm theo nhóm nhiều người nghĩa là học phải có **quy trình** và một **tập các quy tắc**.
**Quy trình** ở đây thường gặp trong các công ty công nghệ hiện nay là **quy trình Scrum**, hãy thử lên mạng tìm kiếm và đọc về quy trình này.
**Quy tắc** ở đây là các chuẩn mực viết code, viết code thế nào cho dễ đọc, dễ hiểu và dễ bảo trình.Kế đến là cách tổ chức cấu trúc một chương trình (Cách tạo thư mục, các đặt tên file, …).
Để biết được các quy tắc viết code và tổ chức code bạn hãy search trên google hai cụm từ khóa là :
- **Node JS styleguide** : Cái này là quy tắt viết code
- **Node js architecture best practices** : Cái này là cách tổ chức và các cách thực hành tốt.
**Styleguide** giống như là tập các quy tắt **clean code** cho một quy tắc cụ thể, thường các bản hướng dẫn tốt đều nằm ở github các bạn chọn những project nhiều star để học nhé ( Google và facebook là những nhà cung cấp Styleguide nhiều nhất và độ tin cậy thống nhất cao nhất)
**Project architecture** : Ngoài đọc các tài liệu trên mạng các bạn cần phải có một hướng tiếp cận đúng để có thể dễ dàng nghiên cứ cái này, và hướng tiếp cận đó gồm những điều đây.
Các project lớn thường xây dựng dựa trên các mộ hình như là **MVC**, mô hình **Webservice**, **Microservice**, ….
Một project thì luôn có những module giúp giao tiếp với **cơ sỡ dữ liệu** thông qua **ORM**, những module để xử lý nghiệp vụ nhưng validation, query data, … và một module ở lớp view để giao tiếp với thế giới bên ngoài. Tất cả đều có một điểm khởi động ở đâu đó, ví dụ như Node JS thì thường là file index.js hoặc file server.js. Đọc ngược từ đây bạn sẽ nắm được dòng hoạt động của một project nhanh hơn.
Các điểm hay của một project Node JS nói riêng thường nằm ở cách tổ chức thư mục và các đặt tên file. Nhìn qua một cấu trúc thư mục các bạn có thể năm được dòng hoạt động của nó dễ dàng.
```markup
.
├── apps
│ ├── client
│ │ └── modules
│ │ └── core
│ ├── server
│ │ ├── configs
│ │ │ ├── env
│ │ │ ├── i18n
│ │ │ └── logs
│ │ ├── controllers
│ │ ├── jobs
│ │ ├── lib
│ │ ├── models
│ │ │ └── DAO
│ │ ├── policys
│ │ ├── routes
│ │ │ ├── api
│ │ │ └── page
│ │ ├── services
│ │ └── views
│ └── test
│ ├── client
│ ├── e2e
│ └── server
├── bin
├── build
├── configs
├── docs
├── public
│ ├── dist
│ ├── images
│ └── uploads
├── scripts
└── tasks
```
Ví dụ ở trên là một cấu trúc thư mục mình hay sử dụng để Code một Project Node JS.
Đầu tiên nhìn vào các bạn sẽ thấy hai thư mục là **client** và **server**. client ở đây chính là các mã lệnh JavaScript ở phía client, mang đến một giao diện người dùng tốt và trực quan cho người dùng, mình thì mình rất quen tay dùng Angular JS. **Server** ở đây chính là code Node ở phía server,để ý sơ qua các bạn sẽ thấy mình có các thư mục chính là controllers , services, routes, models và configs. Trong đó **controllers**, **services** và **models** chính là 3 thư mục đặc trưng trong khi xây dựng một trang web hoặc một **API RESTFul Webservice**. Kế đến mình còn có thư mục configs trong này chứa các cài đặt về môi trường chạy ứng dụng, các **message dành cho việc đa ngôn ngữ** và các thiết lập dành cho việc **logging khi chạy ứng dụng thực tế** để lưu vết lỗi chương trình.
**Để ý các từ mình bôi đậm, vì đó chính là từ khóa để các bạn reseach trên mạng.**
Ngoài ra còn có thể các thư mục như **jobs** thư mục này chứa các mã lệnh dùng để **migration data** - Để cập nhật database chẳng hạn hoặc các **cron jobs** - chạy xóa log hàng tuần hoặc **backup database** , **batch jobs** - để cập nhật một lượng lớn dữ liệu khi bạn cần nó để chạy một tính năng mới.
và không thể thiếu được **policy** đây là nơi chứa các mã lệnh để kiểm tra quyền của người dùng trên một tính năng nào đó, ví dụ bạn không thể để một người dùng A cập nhật thông tin tài khoản của người B, hay User mà vào thẳng trang của của Admin để cập nhật dữ liệu, trong Node JS thì thư việc **ACL** là một thư viện hay được sử dụng cho việc tạo các policy. Tại thời điểm này còn có thể có những thư viện tốt hơn các bạn có thể tra cứu nó với từ khóa **ACL / Roles + Permissions**.
**Lời khuyên** : Thật ra thì sau một thời gian làm với Node, mình cũng hoàn toàn có thể tự viết riêng cho mình các policys dưới dạng **Middleware** rất dễ dàng. Có một lời khuyên được các chuyên gia nói đó là đừng quá phụ thuộc và các bộ thư viện, dùng nó mà không hiểu gì về nó. Hãy mở code nó ra đọc và xem thử liệu mình có cần dùng nó hay không hay có thể tự viết được khi tham khảo nó. Sẽ có một phần phân tích sâu hơn vào luận điểm này.
Để ý thêm các bạn sẽ còn thấy các thư mục như là : **build , docs và public** trong đó :
**build** : là thư mục chưa các **file binary của project**, đây là file thực thi được tạo ra từ mã nguồn có thể chạy trên một hệ điều hành nào đó mà không cần có mã nguồn gốc. Các bạn hãy nghĩ đến việc khi các bạn cần đem sản phẩm đi Demo hoặc chạy ở máy chủ thì không thể để mã nguồn gốc ở đó được , **tránh việc hack và ăn cắp mã nguồn** là việc vô cùng nguy hiểm, việc build thành các file thực thi dưới sự hỗ trợ của công cụ là vô cùng cần thiết. Với Node JS thì **pkg** là một ứng cử viên sáng giá trong công việc này.
Thư mục **docs** thường thì chứa các file .md là các file tài liệu dự án, như là file hướng dẫn sử dụng, hướng dẫn cài đặt, **hướng dẫn sử dụng** các API, v.v. Thường khi viết một tính năng gì đó qua trọng mình luôn ghi vào tài liệu ngay, phòng về sau quên và cũng để sau này các đồng nghiệp hay bạn bè vào thì cũng dễ làm việc cùng hơn.
**public** theo đúng nghĩa là chứa các tài nguyên công khai như là các file JS, CSS hoặc hình ảnh ( JS ở client nha
thư mục **scripts** đây là thư mục thường chưa một số **shell script** để làm việc với hệ điều hành, ví dụ sau này khi bạn cần config một bộ CI hay **auto build, auto deploy** thì bạn sẽ viết các kịch bản shell vào.
ví dụ: để chạy ứng dụng thì cần gõ các lệnh như là.
```markup
git pull
grunt buid
node server
```
các lệnh này sẽ ghi vào các file shell script, tùy vào từng hệ điều hành mà sẽ có loại shell khác nhau.
Thư mục **tests** chứa code test cho ứng dụng để tránh trường hợp khi bạn viết một tính năng mới lại kéo theo lỗi cho một tính năng trước đó đang chạy tốt hoặc một ai đó đã làm sai code của bạn. Các kỹ thuật viết Test hiện nay hay gặp là **TDD (Test-Driven Development)** , **BDD (Behavior Driven Development)**. Tuy nhiên viết code test là rất tốn thời gian, nên để hiệu quả thường chúng ta chỉ viết code test cho những tính năng thật sự quan trọng.
cuối cùng đó là **tasks** đây là thư mục chứa các **file config cho việc auto build và auto deploy**. Thường thì Node JS mình hay **dùng Grunt để làm công cụ build**.
Ví dụ khi viết mã CSS bằng **SASS** thì các bạn cần phải chạy một trình compile để dịch mã SASS sang CSS. Khi deploy một website thì bạn cần **Minify mã CSS , JS và HTML** để tiết kiếm băng thông và tăng tốc độ tải.
Hoặc trong khi code bạn cần một công cụ liên tục check mã mình xem viết có đúng tiêu chuẩn không thì có thể sử dụng **JShint và CSSHint**.
Và còn rất nhiều thứ có thể làm được với Grunt hoặc một công cụ khác đó là Webpack cũng có công dụng gần tương tự .
## Chốt lại phần 2:
Để có được các kiến thức cũng như cập nhật sớm nhất sự thay đổi của công nghệ các bạn **nên theo dõi một opensource project trên github** đọc hiểu Code của Project đó để có thể nhận biết ra sự thay đổi. Mình follow MEAN.JS và Mean project trên Github, hai project này cung cấp cho mình kỹ năng rất nhiều.
Bạn có thể tìm thấy rất nhiều Opensource project tốt tại đây hoặc reseach trên github.
[ Những opensource project Node JS hay ](https://github.com/sqreen/awesome-nodejs-projects)
thứ hai đó là thường xuyên đọc tạp chí hoặc blog công nghệ ở Việt Nam thì [Tech Talk | Xu hướng công nghệ](https://techtalk.vn/) , [Viblo | Free service for technical knowledge sharing](https://viblo.asia/) là những trang khá uy tín và cung cấp thông tin chất lượng nhất. Ngoài ra nếu bạn có thể thì [DZone: Programming & DevOps news, tutorials & tools](https://dzone.com/) là một trang tuyệt vời để cập nhật thông tin tổng quát về công nghệ (Mình rất thích trang này).
(Còn tiếp …. )
Đà Nẵng ngày 6 tháng 10 năm 2017.
<NAME>
**website**: [ sociss.edu.vn - Sociss Class - Online Education Center ](https://sociss.edu.vn/search)
**email** : <EMAIL>
<file_sep>
Trước khi bắt đầu vào khóa học Node JS - Full Stack Dev của mình, mình sẽ giới thiệu trước một số khái niệm cơ bản mà các bạn sẽ gặp
phải trong khóa học. Ngoài ra tên của các khái niệm cũng chính là những từ khóa để các bạn có thể reseach trên mạng để có thể học nhanh hơn.
# 1. Non-blocking hoặc Asynchronous I/O
Đây là đặc trưng của Node.JS,khả năng chạy bất đồng bộ hướng sự kiện giúp tăng cao tổc độ thực thi. Mình sẽ có bài viết riêng cho chủ đề này
để phân tích sâu hơn.
# 2. Prototype
Đây là một khái niệm khá quạn trọng trong Javascript nói chung và Node JS nói riêng. Khái niệm prototype trong Javascript là để ám chỉ về việc kế thừa.
Tuy nhiên một điều cần lưu ý là trong Javascript việc kế thừa trong Javascript không giống như các ngôn ngữ hướng đối tượng như Java hay C++.
# 3. Modules
Module ở đây là khái niệm chỉ việc bạn gom nhóm mã lệnh thành các mô-dun tách thành các file riêng biệt để tăng khả năng sử dụng lại mã lệnh hoặc dễ quản lý hơn.
Mình sẽ có bài viết riêng để làm rõ hơn về cách thức module hóa mã lệnh trong Node JS.
# 4. Callback
Đây là một mô hình lập trình ứng dụng điểm đặc biệt của Javascript đó là bạn có thể truyển vào một hàm A với đối số là một Hàm B khác và triệu gọi thực thi hàm này.
Mình sẽ có bài viết riêng để làm rõ hơn về Callback
# 5. ES6
Đầy là một tiêu chuẩn viết viết code mới của Javascript. Đến thời điểm hiện tại đã có ÉS7 rồi. tuy nhiên ES6 vẫn được sử dụng rộng rãi hơn.
một số tính năng hay của ES6
1) Default Parameters in ES6
2) Template Literals in ES6
3) Multi-line String in ES6
4) Destructuring Assignment in ES6
5) Enhanced Object Literals in ES6
6) Arrow Function in ES6
7) Promises in ES6
8) Block-Scoped Constructs Let and Cont
9) Classes in ES6
10) Modules in ES6
Mình cũng sẽ có riêng một bài viết cho chủ đề này.
<file_sep>Để khởi tạo GIT cho một dự án đã tồn tại hoặc một dự án mới ta làm như sau
# Bước 1
Di chuyển đến thư mục gốc của project đó
<file_sep>var books = [
{id : 1, content : 'This is book 1'}
];
function addBook(_book) {
books.push(_book);
}
function remoteBook(_book) {
}
<file_sep>/**
* @author <NAME>
* @module routes
* @name author.server.routes
*/
"user strict";
let router = require('express').Router();
let AuthorCtrl = require('../controllers').Author;
// Resolve route params
router.param('author', AuthorCtrl.findOne);
// Public routes
router.route('/:author([a-zA-Z0-9.\-_]{8,30})')
.get(AuthorCtrl.renderAuthorPage);
router.route('/:author([a-zA-Z0-9.\-_]{8,30})/posts')
.get(AuthorCtrl.renderAuthorPostsPage);
module.exports = router;
<file_sep>/**
* @module services
* @author <NAME>
* @name author.server.service
*/
"use strict";
let Author = require('../models').Author;
module.exports = {
findByUsernameOrId : findByUsernameOrId,
getAllAuthors : getAllAuthors
};
/**
* @name findByUsernameOrId
* @description
* Find one author by username or id.
*
* @param {string} _param Username or Id of author.
* @return {promise.<object>} Author object.
*/
function findByUsernameOrId(_param) {
// TODO: More business logic code here.
return Author.findOne(_param);
}
/**
* @name getAllAuthors
* @description
* Get all authors in database
*
* @return {promise.<array>} Authors.
*/
function getAllAuthors() {
// TODO: More business logic code here.
return Author.getAll();
}
<file_sep>
initHomePage();
function initHomePage() {
var authors = loadAllAuthor();
}
function onSubmitForm() {
var _numerb = document.getElementById('number').value;
if(_numerb la so ) {
ok
} else {
thong bao message
}
}
function isValidData(data) {
getData()
isValidBook()
isValidAuthor()
isPayment()
throw new Error('Data not valid')
return true;
}
function getData() {
}
function isValidBook() {
}
function isValidAuthor() {
}
<file_sep>Liệt kê danh sách các hành động của GIT tại đây + chi tiết code cho các hành động cụ thể
<file_sep>/**
* @module services
* @author <NAME>
* @name post.server.service
*/
"use strict";
let Post = require('../models').Post;
module.exports = {
findPostsByAuthor : findPostsByAuthor
};
/**
* @name findByUsernameOrId
* @description
* Find one author by username or id.
*
* @param {string} _authorId Author ID.
* @return {promise.<object>} Author object.
*/
function findPostsByAuthor(_param) {
return Post.findPostsByAuthor(_param);
}
<file_sep>let BaseError = require('./BaseError');
class NotFoundError extends BaseError {
constructor(message, isPublic) {
super(message, 404, isPublic);
}
}
module.exports = NotFoundError;
<file_sep>Phần code này đang được viết nên vẫn chưa chạy được nhé.
Cảm ơn các bạn đã quan tâm.
<file_sep>/**
* @author <NAME>
* @module models
* @name post.server.model
*/
"user strict";
let posts = [
{
name : 'Post 1',
author : '1111'
},
{
name : 'Post 2',
author : '1111'
},
{
name : 'Post 3',
author : '1111'
},
{
name : 'Post 4',
author : '1112'
},
];
module.exports = {
findPostsByAuthor : findPostsByAuthor
};
/**
* @name findPostsByAuthor
* @description
* Get all posts of author by author ID.
*
* @param {string} _authorId Author ID.
* @return {promise.<Array>} List Post of author
*/
function findPostsByAuthor(_authorId) {
let _results = posts.filter(_post => _post.author === _authorId);
return new Promise((resolve, reject) => {
resolve(_results);
});
}
<file_sep># sociss-class-nodejs
Base project for teaching and learing Node JS.
<file_sep># common-statements
Trong ví dụ này chỉ ra các câu lệnh cơ bản hay gặp trong lập trình Node JS.
## I. Vòng lặp for
Trong Node JS vòng lặp có thể được khai báo như sau.
```javascript
for(var i=0; i<= 5; i++) {
console.log(i);
}
```
Ở ví dụ trên là biểu thức vòng lòng giống như ngôn ngữ lập trình C hay C++.
Ngoài ra con có nhiều kiểu khác như là :
#### 1. Loop in
```javascript
var arrays = ['A', 'B', 'C', 'D', 'E'];
for(var item in arrays) {
console.log(arrays[item]);
}
```
Đây đơn giản là một biến thể của vòng for loop ban đầu. Lúc này chúng ta không cần tăng biến điếm nữa, mặc định `item` sẽ giữ giá trị index của mảng, vì vậy khi cần truy xuất giá trị một phần tử của mảng ta đơn giản dùng `arrays[item]`
#### 2. For loop
```javascript
arrays.forEach(function onEachItem(_item) {
console.log(_item);
});
```
Đây là một method hỗ trợ trong ES5, giúp cho việc tương tác với mảng trở nên thuận tiện hơn.
Chú ý: `forEach` là một hàm bất đồng bộ, nghĩa là nó không theo thứ tự dòng lệnh trên mã.
Ví dụ:
```javascript
arrays.forEach(function onEachItem(_item) {
console.log(_item);
});
console.log('It will call before loop print console done.');
```
Theo suy nghĩ thông thường thì lệnh `console.log` thứ hai sẽ in ra sau, tuy nhiên như nói trên hàm forEach là bất đồng bộ nên nó sẽ chạy ra trước khi hàm forEach in xong giá trị ra console.
# II. Câu lệnh If Else
```javascript
function isMorning(time) {
if(!time) return false;
if(time === 'morning') {
return true;
}
else {
return false;
}
}
```
# III. Câu lệnh Switch Case
Sử dụng để thực hiện một tập lệnh rẽ nhánh dựa trên một biểu thức đầu vào.
```javascript
switch (time) {
case 'morning': {
console.log('Good Morning.');
break;
}
case 'afternoon': {
console.log('Good afternoon.');
break;
}
case 'evening': {
console.log('Good evening.');
break;
}
default: {
console.log('I dont know.');
}
}
```
# IV. Thao tác với JSON
Trong Node JS, làm việc với dữ liệu định dạng JSON là việc thường xuyên gặp. Như là xử lý dữ liệu trả về từ API hay việc làm việc với Cơ sở dữ liệu Mongo DB.
Ví dụ: Dưới đây, mình sẽ định nghĩa một object đơn giản với ba thuộc tính là name, age và job. Sau đó mình sẽ thực hiện lần lượt hai việc là
1. Chuyển đổi từ Objet sang chuỗi JSON.
2. Chuyển đổi từ chuỗi JSON sang Object.
3. Bắt ngoại lệ khi đầu vào của việc chuyển đổi là không hợp lệ.
> Trong khi chuyển đổi qua lại JSON , bạn nên nhớ try-catch vì rất dễ xảy ra
> lỗi gây sập chương trình.
```javascript
// JS object define.
var object = {
name : '<NAME>',
age : 20,
job : 'Developer'
};
// Cover object to JSON string.
var JSONStr = JSON.stringify(object);
console.log('Should be string :', typeof JSONStr === 'string');
// Cover JSON string to object.
var _object = JSON.parse(JSONStr);
console.log('Should be object: ', typeof _object === 'object');
// Catch exception when on invalid input data.
try {
JSON.parse('THIS IS NOT JSON STRING, WILL FIRE ERROR !!!');
} catch (e) {
console.log('Should have error on invalid input: ', e !== undefined);
}
```
<file_sep>"user strict";
// Module public methods.
module.exports = {
renderHomePage : renderHomePage,
renderContactPage : renderContact
};
/**
* @name renderHomePage
* @description
* Render homepage.
*
* @param {object} req HTTP request
* @param {object} res HTTP response
*/
function renderHomePage(req, res) {
res.render('homepage', {
content : 'This is homepage content'
});
}
/**
* @name renderContact
* @description
* Render contact page.
*
* @param {object} req HTTP request
* @param {object} res HTTP response
*/
function renderContact(req, res) {
res.render('contact', {
content : 'This is contact page content'
});
}
<file_sep># Hướng dẫn cách cài đặt GIT
Để cài đặt Git
<file_sep>"user strict";
const coreRoutes = require('./core.server.routes');
module.exports = function(app) {
coreRoutes(app);
};
<file_sep>#require-module
### Để chạy ví dụ sử dụng lệnh.
```
cd /simple-require-module
node index
```
### Mô tả
Ví dụ này hướng dẫn bạn cách sử dụng một module tự viết. Việc tách ứng dụng
thành nhiều module là việc cần thiết để cho mã nguồn dễ quản lý hơn.
Module là giống như các thư viện trong PHP, C, C#,… Mỗi module chứa một tập các hàm chức năng có liên quan đến một đối tượng của Module qua đó giúp việc viết và quản lý mã lệnh của chương trình được dễ dàng hơn. Một module có thể đơn giản là một hàm hay một đối tượng. Mỗi module thường được khai bảo ở một tập tin riêng rẽ.
Trong Node JS để gọi một module chứa trong một file .js khác ta sử dụng require.
ví dụ:
```javascript
var Operator = require('./lib/Operator');
```
Như đoạn code ở trên có nghĩa là chúng ta sẽ khởi tạo một đối tượng Operator
chứa trong thư mục lib. Ký hiệu './' ở đây là để chỉ tìm kiếm bắt đầu từ thư
mục hiện hành.
```javascript
module.exports.add = function Add(a, b) {
return a + b;
};
```
Từ khóa module.exports ở đây là để xuất hay public một thuộc tính hay phương thức trong module ra ngoài. Sau khi exports chúng ta có thể sử dụng được hàm
add sau khi require nó vào.
```javascript
var a = 5;
var b = 5;
console.log(Operator.add(a, b));
```
Kết quả lúc này sẽ là 10.
<file_sep>/**
* @module routes
* @description
* Define all core routes of applications
*/
"user strict";
const coreCtrl = require('../controllers').Core;
module.exports = function(app) {
app.route('/').get(coreCtrl.renderHomePage);
app.route('/contact').get(coreCtrl.renderContactPage);
};
<file_sep># Kiến thức nền
Ứng dụng Node JS được viết trên mã lệnh JavaScript. Những bạn trước đây đã làm việc quen với JavaScript trên trình duyệt thì sẽ thấy rất cấu trúc câu lệnh gần như tương đồng tuy nhiên chỉ khác nhau ở điểm đó là.
>Mã JavaScript trong Node JS là chạy ở phía Server Side nên sẽ không hỗ trợ các câu lệnh tưng tác với DOM hay những Browser Library để làm việc với trình duyệt thay vào đó, Node JS sẽ hỗ trợ những thư viện để chúng ta có thể làm việc với tệp tin, hệ điều hành, v.v.
Trong bài viết này mình Quyền sẽ giới thiệu cho các bạn tổng quát kiến thức nền cần thiết khi làm việc với ngôn ngữ JavaScript bao gồm 3 phần trọng tâm là .
1. Cấu trúc câu lệnh.
2. Kiểu dữ liệu.
3. Thao tác trên các kiểu dữ liệu.
## 1. Cấu trúc câu lệnh JavaScript
### 1.1 Khối lệnh và dòng lệnh
Như các ngôn ngữ họ C khác như Java, .NET, v.v .JavaScript cũng tương tự, các khối mã lệnh được đặt trong cặp dấú ngoặc nhọn `{ code block }`. Kết thúc mỗi dòng lệnh sẽ là dấu chấm phẩy `;`.
Ví dụ về khối lệnh và dòng lệnh.
```javascript
function doSomethingCool() {
// Đây là một khối lệnh trong cặp dấu ngoặc nhọn.
// Dòng lệnh trong khối lệnh kết thúc bằng dấu chấm phẩy.
console.log('Line 1');
console.log('Line 2');
console.log('Line 3');
}
```
### 1.2 Từ khóa
Trong JavaScript có bộ từ khóa là:
Từ khóa | Ý nghĩa
-------------------|------------------------------------------
break | Thoát khỏi câu lệnh Switch hoặc vòng lặp
continue | Nhảy ra khỏi vòng lặp hiện tại và quay trở lại đầu vòng lặp kế tiếp
debugger | Dùng để đặt một break point khi debug
do ... while | Thực thi câu lệnh trong khối Do khi điều kiện trong While còn đúng
if ... else | Khối lệnh điều kiện rẽ nhánh.
return | Trả về giá trị và thoát khỏi một hàm.
switch | Đánh dấu một block gồm nhiều khối lệnh khác nhau sẽ được thực thi phụ thuộc vào từng trường hợp cụ thể của dữ liệu vào.
try ... catch | Bắt và xử lý lỗi (Ngoại lệ)
var | Định nghĩa biến.
Ví dụ một đoạn lệnh nhỏ.
```javascript
var a = 1;
var b = 2;
console.log(a + b); // 3
```
Câu lệnh trên khi thực thi sẽ in ra màn hình terminal giá trị là 3.
### 1.3 Comment (Viết bình luận hoặc mô tả cho mã lệnh)
Khi viết chương trình thì việc comment hay viết lời bình luận cho câu lệnh là không
thể thiếu. Cũng như các ngôn ngữ khác JS có hai kiểu comment là comment trên một dòng
hoặc comment trên nhiều dòng.
comment trên một dòng bắt đầu với //
còn comment trên nhiều dòng bắt đầu với /* và kết thúc với * /
Ví dụ về viết document cho hàm Add thực hiện việc cộng hai số a và b.
```javascript
/**
* @name Add
* @description
* Add two given number {a} and {b} .
*
* @param {number} a First number
* @param {number} b Second number
* @constructor
*/
function Add(a, b) {
// return sum of a and b.
return a + b;
};
```
## 2. Biến và toán tử
Trong JS biến được khai báo với từ khóa `var`. Và có các kiểu dữ liệu là Object (đối tượng), String (Chuỗi), Number (Số ) hoặc Array (Mảng).
Ví dụ:
```javascript
var MAX = 1000; // Number
var name = "<NAME>"; // String
var user = { // Object
name:"<NAME>",
username: "nghuuquyen"
};
var array = ['Happy', 'Learning', 'Node JS']; // Array
```
Tương ứng với mỗi kiểu dữ liệu sẽ có một số thao tác cơ bản.
### 2.1 Kiểu dữ liệu đối tượng ( Object )
#### 2.1.1 Khai báo
Trong JS mỗi đối tượng gồm có hai phần cơ bản đó là các thuộc tính (properties)
và các phương thức (methods) hay còn gọi là hành vi của đối tượng.
Ví dụ khai báo một object đơn giản.
```javascript
var product = {
name : 'Product A',
price : 500,
fullInfo : function getFullInfo() {
return 'Name: ' + this.name + ' Price: ' + this.price;
}
};
```
Trong ví dụ trên ta thấy đối tượng `product` có 2 thuộc tính là `name` và `price`
trong đó thuộc tính `name` có giá trị (Property Value) là `Product A`.
Ngoài ra object `product` còn có một phương thức đó chính là `fullInfo` để trả
về thông tin đầy đủ của đối tượng là một chuỗi gồm tên và giá.
#### 2.1.2 Thiết lập và truy xuất dữ liệu (Get và Set Data)
Để thiết lập giá trị (Set) cho thuộc tính của đối tượng ta có hai cách như sau
```javascript
product.name = 'New Name';
product['name'] = 'New Name';
```
Việc lấy dữ liệu cũng đơn giản
```javascript
var _name = product.name;
```
Hoặc
```javascript
var _name = product['name'];
```
#### 2.1.3 Thực thi phương thức
Để thực thi phương thức của object các bạn làm như sau.
```javascript
var _fullInfo = product.fullInfo();
```
### 2.1 Kiểu dữ liệu chuỗi ( String )
#### 2.1.1 Khai báo
```javascript
var _string = 'This is string.';
// Nếu trong chuỗi có ký tự đặt biệt thì có thể dùng ký hiệu thoát \
var _message = 'It\'s 7 o\'clock.';
```
#### 2.1.2 Các thuộc tính và phương thức hay dùng trên chuỗi
**1. Lấy độ dài chuỗi.**
```javascript
var _string = 'THIS IS STRING';
_string.length // Get string length.
```
**2. Viết thường hoặc viết hoa tất cả.**
```javascript
var _string = 'THIS IS STRING';
var a = _string.toLowerCase(); // a = 'this is string'
var b = _string.toUpperCase(); // b = 'THIS IS STRING'
```
**3. Cắt bỏ ký tự trống hai đầu.**
Phương thức này được dùng thường xuyên để xử lý chuỗi vào, tránh bị dư thừa ký
tự trống hai đầu.
```javascript
var _string = ' THIS IS STRING ';
var a = _string.trim(); // a = 'THIS IS STRING'
```
### 2.2 Kiểu dữ liệu số ( Number )
#### 2.2.1 Khai báo
Khai báo một biến kiểu số.
```javascript
var _number = 150;
```
#### 2.2.2 Đối tượnng Math để thao tác trên số.
trong JS Math là một biến Global các bạn có thể dùng luôn mà không cần khai báo.
**1. Làm tròn số.**
Để làm tròn số thì trong JS có hỗ trợ 3 kiểu, làm tròn gần nhất (round), làm tròn
lên (ceil) và làm tròn xuống (floor).
Làm tròn gần nhất sẽ trả về giá trị nguyên gần nhất với giá trị hiện tại.
```javascript
Math.round(4.7); // trả về 5
Math.round(4.4); // trả về 4
```
Làm tròn lên và làm tròn xuống.
```javascript
Math.floor(4.7); // trả về 4
Math.ceil(4.4); // trả về 5
```
**2. Tính trị tuyệt đối**
```javascript
Math.abs(-5); // trả về 5
```
**3. Tính sin và cos**
hàm sin và cos nhận và giá trị radians, nếu bạn muốn dùng bằng giá trị độ, thì
đơn giản là nhân cho số PI rồi chia cho 180.
```javascript
Math.sin(90 * Math.PI / 180); // trả về 1 (Sin góc 90 độ)
```
**4. Tính giá trị mũ (x mũ y )**
```javascript
Math.pow(8, 2); // trả về 64 vì là 8 mũ 2
```
**5. Tính giá trị căn bật hai**
```javascript
Math.sqrt(64); // trả về 8
```
**6. Lấy giá trị ngẫu nhiên.**
Hàm random() sẽ trả về ngẫu nhiên một giá trị trong khoảng từ 0 đến 1.
Ví dụ để lấy ngẫu nhiên một số trong khoảng từ 0 đến 1000 thì có thể làm như sau.
```javascript
Math.round( Math.random() * 1000 );
```
### 2.3 Kiểu dữ liệu mảng ( Array )
#### 2.2.1 Khai báo
Khai báo một biến kiểu mảng.
```javascript
var _numArray = [1, 2, 3, 4, 5]; // Khai báo một mảng số.
var _strArray = ['a', 'b', 'c']; // Khai báo một mảng ký tự.
var _oArray = [ // Khai báo một mảng đối tượng.
{name : 'Product A', price : 500},
{name : 'Product B', price : 600},
{name : 'Product C', price : 700}
] ;
```
#### 2.2.2 các thuộc tính và phương thức thao tác với mảng.
**1. Lấy độ dài mảng**
```javascript
var array = [1,2,3];
array.length // 3
```
**2. Thêm phần tử vào mảng**
a. `push` thêm vào cuối.
```javascript
var array = [1,2,3];
array.push(4) // array = [1,2,3,4]
```
b. `unshift` thêm vào đầu mảng
```javascript
var array = [1,2,3,4,5];
array.unshift(0) // array = [0,1,2,3,4,5]
```
**3. Đọc giá trị trên mảng.**
```javascript
var array = [1,2,3];
array[1] // 2 , đọc tại vị trí 1, đếm từ 0.
```
**4. Lấy phần tử trên mảng ra**
Có 3 kiểu lấy phần tử ra đó là lấy đầu, lấy cuối và lấy ở vị trí `i`. Chú ý khi lấy
ra xong thì phần tử đó cũng xóa trong mảng gốc.
a. `pop` lấy cuối.
```javascript
var array = [1,2,3,4,5];
array.pop() // 5, lấy phần từ ở cuối ra.
```
b. `shift` lấy đầu
```javascript
var array = [1,2,3,4,5];
array.shift() // 1, lấy phần từ ở cuối ra.
```
**5. Cắt mảng (tạo một mảng con từ mảng gốc ban đầu)**
hàm `slice` nhận vào hai tham số bắt đầu và kết thúc. Chú ý nếu chỉ đưa vào một
tham số thì xem như là cắt từ vị trí đó đến cuối mảng.
Chú ý như ví dụ đây thì vị trí kết thúc sẽ không bao gồm trong mảng con nhé.
```javascript
var array = [1,2,3,4,5];
var sub = array.slice(1, 3); // cắt từ index 1 đến 3, sub = [2,3]
```
Ví dụ cắt từ vị trí số 3 đến tận cùng mảng.
```javascript
var array = [1,2,3,4,5];
array.slice(3) // [4,5]
```
**6. Sắp xếp mảng**
Để sắp xếp mảng thì JS hỗ trợ cho bạn một phương thức `sort`. Nguyên tắc làm việc của hàm `sort` này là đem so sánh từng cặp giá trị của 2 số, sau đó tùy theo giá trị trả về.
Nếu trả về số âm -> phần tử `a` nhỏ hơn `b`.
Nếu trả về số dương -> phần tử `a` lớn hơn `b`.
Nếu bằng 0 -> phần tử `a` bằng `b`.
Áp dụng nguyên tắc trên mình sẽ viết một hàm `doSort` nhận hai tham số đầu vào là `a` và `b`. sau đó thực hiện so sánh bằng cách trả về giá trị `a - b`.
Ví dụ:
a = 40; b = 50
Vì a - b = -10 nên a < b;
```javascript
var points = [40, 100, 1, 5, 25, 10];
points.sort(doSort); // [1, 5, 10, 25, 40, 100];
function doSort(a,b) {
return a - b;
}
```
> Chú ý viết `points.sort(doSort);` là cách viết theo kiểu đối số là một hàm, các bạn có thể đọc phần JavaScript Callback ở mục dưới để hiểu rõ hơn về phong cách viết này.
Áp dụng tư tưởng trên chúng ta có thể cải tiến hàm trên để sắp xếp mảng sinh viên theo điểm tăng dần như sau.
```javascript
var students = [
{ name : 'Student A', points : 85 },
{ name : 'Student C', points : 56 },
{ name : 'Student K', points : 63 },
{ name : 'Student E', points : 71 },
{ name : 'Student F', points : 25 },
];
function doSortStudent(a,b) {
return a.points - b.points;
}
students.sort(doSortStudent);
for(student in students) {
console.log(students[student].points);
}
```
### 2.3 Hàm ( Function )
Việc sử dụng hàm không còn xa lạ gì với kỹ thuật lập trình, trong JS việc khai
báo một hàm có thể thực hiện như sau.
#### 2.3.1 Khai báo
```javascript
function addTwoNumbers(a,b) {
return a + b;
}
```
Trong đó `function` là từ khóa khai báo hàm. `addTwoNumbers` là tên hàm,
`(a,b)` là danh sách đối số. `return` là từ khóa trả về giá trị hàm đồng thời cũng thoát khỏi hàm đó.
#### 2.3.2 Gọi một hàm ra sử dụng.
Để gọi hàm chúng ta đơn giả sử dụng cặp dấu ngoặc tròn `()` kèm bên theo danh
sách đối số nếu có.
```javascript
function addTwoNumbers(a,b) {
return a + b;
}
// Gọi hàm
addTwoNumbers(5,3) // trả về 8
```
#### 3.3.3 Callback trong JavaScript
**a. Khái niệm và cách tiếp cận**
Trong khi làm việc với JavaScript bạn sẽ rất tường xuyên nghe đến khái niệm Callback.Callback có thể hiểu là việc bạn truyền vào một hàm khác tạm gọi là B đối số là một `function` tạm gọi là A. Sau đó việc triệu gọi function A bạn truyền vào sẽ phụ thuộc function B kìa.
Callback ở đây là gọi ngược, tức là cái function này gọi ngược lại function kia.
Để dễ hiểu hơn mình sẽ đưa ra ví dụ sau.
Giả sử yêu cầu bạn viết một hàm mở cơ sở dữ liệu và tìm kiếm một sinh viên theo `ID`, đồng thời xử lý 3 trường hợp đó là
1. tìm thấy sinh viên
2. không tìm thấy sinh viên
3. Xảy ra lỗi nào đó (như mất kết nối, ...)
Thì với yêu cầu trên thì có bạn sẽ viết theo kiểu là hàm `find` sẽ trả về `object` nếu tìm thấy hoặc `null` nếu không tìm thấy, và đồng thời ném ra ngoại lệ nếu gặp lỗi.
Mình sẽ viết mô phỏng code như sau.
```javascript
function findStudentByID(id) {
if(!id) throw new Error('id param is undefined !');
try {
/**
* Tìm kiếm gì đó ở đây, nếu thầy thì trả về student
* nếu không thì trả về null.
*/
} catch (error) {
// Nếu gặp bất kỳ lỗi nào thì ném ra.
throw error;
}
}
// Gọi hàm để dùng phải sử dụng try-catch để bắt lỗi.
try {
var _result = findStudentByID(5);
if(!_result) {
console.log('Student not found');
} else {
console.log('Found student.');
}
} catch (e) {
// Gọi hàm để xử lý lỗi ở đây. có thể dựa trên mã lỗi
// e.code === 400 => notFound
// e.code === 500 => error
console.error(e);
}
```
Qua đoạn code trên thấy nhiều hạn chế như là.
1. Code không đẹp, không rõ ràng vì có nhiều try-catch.
2. Tại lúc catch khi dùng hàm `findStudentByID` ta thấy phải if-else hoặc switch-case để xử lý lỗi trả về.
=> Nhìn chung là khá phức tạp.
Tuy nhiên nếu tiếp cận theo mô hình `callback` thì vấn để trên sẽ giải quyết như sau.
```javascript
function findStudentByID(id, success, notFound, error) {
if(!id) error(new Error('id param is undefined !'));
try {
/**
* Tìm kiếm gì đó ở đây, nếu thầy thì trả về student
* nếu không thì trả về null.
*/
if (nếu tìm thầy) {
// Gọi function success với đói số vào chính là giá trị
// student tìm thấy.
success(student);
}
// Nếu không thì gọi notFound để xử lý không tìm thấy.
notFound();
} catch (e) {
// Nếu gặp bất kỳ lỗi nào thì gọi error để xử lý lỗi.
error(e)
}
}
// Hàm xử lý khi tìm thấy.
function onSuccess(_student) {
console.log('Found student !!!');
console.log(_student);
}
// Hàm xử lý khi bị lỗi.
function onError(err) {
console.log('Has error !!!');
console.log(err);
}
// Hàm xử lý khi không tìm thấy.
function onNotFound() {
console.log('Student not found !!!');
}
// Sử dụng.
findStudentByID(5,onSuccess, onNotFound, onError);
```
Qua cách tiếp cận callback trên các bạn có thể thấy ngay là mã lệnh bây giờ trở nên rất đẹp và dễ hiểu đúng không nào.
**b. Ứng dụng trong xử lý bất đồng bộ**
Không chỉ dừng lại ở việc design pattern như trên, callback còn được xử dụng và cũng chính là core của NodeJS.
Đầu tiên như thế nào là `xử lý đồng bộ`. Chúng ta có thể hình dung như sau, giả xử một hàm tìm sinh viên từ cơ sở dữ liệu như trên theo ID gồm các thao tác sau.
1. mở kết nối
2. thực thi tìm kiếm
3. trả kết quả
trong đó việc mở kết nối mất đến 10 giây vì mạng chậm, như vậy nếu theo xử lý đồng bộ thì tất cả các công việc sẽ phải dừng lại chờ đủ 10 giây để hàm trên làm xong và trả về kết quả thì mới thực thi tiếp được --> việc này dẫn đến chậm trễ do chờ tài nguyên.
cơ chế callback sẽ khắc phục được nhược điểm đó, xem đoạn code ví dụ dưới đây.
```javascript
function doSomethingCool(message, callback) {
// Hàm này sẽ delay 10 giây.
setTimeout(function callAfter10Sec() {
// Sau 10 giây sẽ gọi callback với đối số message.
callback(message);
}, 10000);
}
doSomethingCool('Done', function onDone(message) {
console.log('Callback :: ' + message);
});
console.log('Do something 1');
console.log('Do something 2');
console.log('Do something 3');
```
Qua đoạn code trên các bạn thấy rằng khối lệnh
```javascript
console.log('Do something 1');
console.log('Do something 2');
console.log('Do something 3');
```
không hề chờ mà thực thi luôn, sau đó 10 giây thì hàm `onDone` mới thực thi, nhờ đó tốc độ chương trình sẽ tăng rất nhiều.
**c. Lưu ý khi sử dụng callback**
khi viết mã bất đồng bộ, nghĩa là các bạn phải nắm rõ khi nào nó đồng bộ (có dữ liệu) để xử lý logic code cho đúng tránh bị lỗi. Ví dụ
```javascript
var message;
function handleData(data) {
// do something when have data.
}
doSomethingCool('Done', function onDone(_data) {
message = _data;
console.log(message); // -> Done
// Khi có dữ liệu mới gọi hàm xử lý.
handleData();
});
// Tại đây không có dữ liệu nên phải chú ý.
console.log(message); // -> undefined
```
Các bạn thấy nếu các bạn log message ra ở ngoài hàm callback thì tại đó không có dữ liệu.
Ngoài ra khi lạm dụng callback thì sẽ trở thành 'callback hell' địa ngục callback ám chỉ việc gọi lồng quá nhiều callback gây rối, ví dụ
```javascript
var message;
function handleData(data) {
// do something when have data.
}
doSomethingCool('Done', function onDone(_data) {
// Khi có dữ liệu mới gọi hàm xử lý.
handleData(_data, function cb1(_data) {
cb2(_data, function cb3(_data) {
cb4(_data, function cb5(_data) {
cb6(_data, function cb7(_data) {
cb8(_data, function cb0(_data) {
// Và còn nhiều hơn nữa.
});
});
});
});
});
});
```
Thật kinh khủng nếu phải đọc đoạn code trên đúng không nào, thì mình sẽ gọi ý một từ khóa đó chính là `promise` nó sẽ giúp xử lý việc `callback hell` ở trên. Trong phạm vi bài học này mình sẽ không đề cập, tuy nhiên mình sẽ nói ở một bài học khác về việc
`áp dụng promise trong xử lý callback hell`.
## Các cấu trúc câu lệnh thường gặp
Trong ví dụ này chỉ ra các câu lệnh cơ bản hay gặp trong lập trình Node JS.
## I. Vòng lặp for
Trong Node JS vòng lặp có thể được khai báo như sau.
```javascript
for(var i=0; i<= 5; i++) {
console.log(i);
}
```
Ở ví dụ trên là biểu thức vòng lòng giống như ngôn ngữ lập trình C hay C++.
Ngoài ra con có nhiều kiểu khác như là :
#### 1. Loop in
```javascript
var arrays = ['A', 'B', 'C', 'D', 'E'];
for(var item in arrays) {
console.log(arrays[item]);
}
```
Đây đơn giản là một biến thể của vòng for loop ban đầu. Lúc này chúng ta không cần tăng biến điếm nữa, mặc định `item` sẽ giữ giá trị index của mảng, vì vậy khi cần truy xuất giá trị một phần tử của mảng ta đơn giản dùng `arrays[item]`
#### 2. For loop
```javascript
arrays.forEach(function onEachItem(_item) {
console.log(_item);
});
```
Đây là một method hỗ trợ trong ES5, giúp cho việc tương tác với mảng trở nên thuận tiện hơn.
Chú ý: `forEach` là một hàm bất đồng bộ, nghĩa là nó không theo thứ tự dòng lệnh trên mã.
Ví dụ:
```javascript
arrays.forEach(function onEachItem(_item) {
console.log(_item);
});
console.log('It will call before loop print console done.');
```
Theo suy nghĩ thông thường thì lệnh `console.log` thứ hai sẽ in ra sau, tuy nhiên như nói trên hàm forEach là bất đồng bộ nên nó sẽ chạy ra trước khi hàm forEach in xong giá trị ra console.
# II. Câu lệnh If Else
```javascript
function isMorning(time) {
if(!time) return false;
if(time === 'morning') {
return true;
}
else {
return false;
}
}
```
# III. Câu lệnh Switch Case
Sử dụng để thực hiện một tập lệnh rẽ nhánh dựa trên một biểu thức đầu vào.
```javascript
switch (time) {
case 'morning': {
console.log('Good Morning.');
break;
}
case 'afternoon': {
console.log('Good afternoon.');
break;
}
case 'evening': {
console.log('Good evening.');
break;
}
default: {
console.log('I dont know.');
}
}
```
# IV. Thao tác với JSON
Trong Node JS, làm việc với dữ liệu định dạng JSON là việc thường xuyên gặp. Như là xử lý dữ liệu trả về từ API hay việc làm việc với Cơ sở dữ liệu Mongo DB.
Ví dụ: Dưới đây, mình sẽ định nghĩa một object đơn giản với ba thuộc tính là name, age và job. Sau đó mình sẽ thực hiện lần lượt hai việc là
1. Chuyển đổi từ Objet sang chuỗi JSON.
2. Chuyển đổi từ chuỗi JSON sang Object.
3. Bắt ngoại lệ khi đầu vào của việc chuyển đổi là không hợp lệ.
> Trong khi chuyển đổi qua lại JSON , bạn nên nhớ try-catch vì rất dễ xảy ra
> lỗi gây sập chương trình.
```javascript
// JS object define.
var object = {
name : '<NAME>',
age : 20,
job : 'Developer'
};
// Cover object to JSON string.
var JSONStr = JSON.stringify(object);
console.log('Should be string :', typeof JSONStr === 'string');
// Cover JSON string to object.
var _object = JSON.parse(JSONStr);
console.log('Should be object: ', typeof _object === 'object');
// Catch exception when on invalid input data.
try {
JSON.parse('THIS IS NOT JSON STRING, WILL FIRE ERROR !!!');
} catch (e) {
console.log('Should have error on invalid input: ', e !== undefined);
}
```
# Kết bài
Nhưng vậy qua bài học này Quyền đã giới thiệu cho các bạn sơ qua về những kiến thức
thường gặp khi làm việc với ngôn ngữ lập trình JavaScript. Bao gồm cấu trúc chương trình, các kiểu dữ liệu và các thao tác trên từng kiểu dữ liệu.
Ngoài ra các bạn còn cần nắm thêm các cấu trúc lệnh cơ bản của JS như vòng lặp(for, do while, while), các lệnh rẽ nhánh (Switch-case, if-else) để có thể thực hiện các thuật toán trên dữ liệu.
Đà Nẵng, Ngày 1 tháng 10 năm 2017.
<NAME>
<file_sep>/**
* @author <NAME>
* @module routes
* @description
* Active all routes of application and simple handle error.
*/
"user strict";
let router = require('express').Router();
let NotFoundError = require('../errors/NotFoundError');
// Application routes
router.use('/', require('./core.server.routes'));
router.use('/author', require('./author.server.routes'));
// catch 404 and forward to error handler
router.use((req, res, next) => {
const err = new NotFoundError('Page not found');
return next(err);
});
// Error handle
router.use(function(err, req, res, next) {
const _status = err.status || 500;
res.status(_status);
res.render('error', {
message: err.message,
status : _status
});
});
module.exports = router;
<file_sep>/**
* @author <NAME>
* @module models
* @name author.server.model
*/
"user strict";
let NotFoundError = require('../errors/NotFoundError');
let authors = [
{
id : '1111',
fullName : '<NAME>',
username : 'author_a'
},
{
id : '1112',
fullName : '<NAME>',
username : 'author_b'
}
];
module.exports = {
findOne : findOne,
getAll : getAll
};
/**
* @name getAll
* @description
* Get all authors.
*
* @return {promise.<array>} List of authors.
*/
function getAll() {
return new Promise((resolve, reject) => {
resolve(authors);
});
}
/**
* @name findOne
* @description
* Find one author by username or id.
*
* @param {string} _id username or id
* @return {promose.<object>} Author object.
*/
function findOne(_id) {
return new Promise(( resolve, reject ) => {
for(i in authors) {
if(authors[i].id === _id || authors[i].username === _id) {
return resolve(authors[i]);
}
}
reject(new NotFoundError(`Not found author with id or user name equal ${_id}`));
});
}
<file_sep>var examples = require('./examples');
<file_sep>"use strict";
const express = require('express');
const app = express();
const port = 3000;
let hbs = require('express-hbs');
// Do Registration routes.
app.use(require('./app/routes'));
// Set static content.
app.use('/', express.static('./public'));
// Set view template engine for file extension server.view.html
app.engine('server.view.html', hbs.express4({
extname: '.server.view.html'
}));
// Set view engine
app.set('view engine', 'server.view.html');
// Set views folder
app.set('views', './app/views');
app.listen(port, function(err) {
if(err) {
console.error('Something error !!');
console.error(err);
}
console.log('App listen on port ' + port);
});
<file_sep>// JS object define.
var object = {
name : '<NAME>',
age : 20,
job : 'Developer'
};
// Cover object to JSON string.
var JSONStr = JSON.stringify(object);
console.log('Should be string :', typeof JSONStr === 'string');
// Cover JSON string to object.
var _object = JSON.parse(JSONStr);
console.log('Should be object: ', typeof _object === 'object');
// Catch exception when on invalid input data.
try {
JSON.parse('THIS IS NOT JSON STRING, WILL FIRE ERROR !!!');
} catch (e) {
console.log('Should have error on invalid input: ', e !== undefined);
}
<file_sep>/**
* @author <NAME>
* @module routes
* @name core.server.routes
*/
"user strict";
let router = require('express').Router();
let CoreCtrl = require('../controllers').Core;
router.route('/').get(CoreCtrl.renderHomePage);
module.exports = router;
<file_sep>Liệt kê một số trường hợp GIT hay gặp và hướng giải quyết cụ thể
<file_sep>var authors = [
{
name : 'Quyen',
books : [
{ id : 1 }
]
}
];
function addAuthor() {
}
function removeAuthor() {
}
<file_sep>var Person = require('./lib/Person');
person = new Person('<NAME>', 23);
console.log(person.age);
<file_sep># 1. Giới thiệu
Bài học này chúng ta sẽ bắt tay vào xây dựng một website tĩnh với Node.js. Kiến thức trong mỗi bài học sẽ bắt đầu phức tạp dần.
# 2. Mục tiêu đạt được trong bài học
1) Sử dụng được framework Express.js để khởi tạo và định tuyến đường dẫn cho website.
2) Khai báo và sử dụng được các tài nguyên tĩnh như là các tệp tin js, css và hình ảnh.
3) Hiểu được căn bản cấu trúc một website theo mô hình MVC.
4) Thực hành module hóa trong Node.js
# 3. Công cụ và kiến thức cần thiết
### Công cụ
1) Node JS và NPM
2) Máy tính nối mạng Internet
3) Text Editor như Atom, Sublime hoặc Visual Studio Code
### Kiến thức
Nếu đây là lần đầu tiên bạn đến với Node.js thì bạn nên xem lại các bài học trước đó tại đây. Vì để bắt đầu phần này bạn cần có kiến thức nền trước.
Bài học liên kết với bài học này là [Tạo HTTP web server với Node.js](https://sociss.edu.vn/courses/nodejs/lesson/tao-http-web-server-voi-nodejs)
Các bạn nên đọc qua bài trên trước để hiểu hơn các từ mình dùng cho bài này, và cũng để hiểu hơn về bản chất bên dưới các framework họ làm cái gì.
# 4. Nội dung bài học
## 4.1 Giới thiệu và cài đặt framework Express.js
### Tổng quát bài học
Các bạn biết rằng một yêu cầu đến website sẽ hoạt động theo các bước như sau.
1) người dùng mở trình duyệt lên, gọi một URL nào đó đến webserver của chúng ta
2) Server tiếp nhận URL và thực hiện các hành động tưng ứng và trả về một trang HTML
3) Trình duyệt người dùng tiếp nhận trang HTML đó và hiển thị lên màn hình.
4) Trong quá trình hiển thị lên trang HTML thì trình duyệt sẽ phải tải về các tài nguyên tĩnh chính là các hình ảnh, tệp tin javascript và css.
Bài học của chúng ta cũng có các phần tưng ứng với các bước đó.
**Trong phần đầu tiên**
mình sẽ hướng dẫn cách sử dụng Express.js để khởi tạo một HTTP server, định tuyến và mapping (gắn) các controller (chứa các function handler) tứng ứng để đáp ứng các yêu cầu
**Phần thứ hai**
Mình sẽ hướng dẫn các bạn thiết lập **view engine** là công cụ để các bạn trả về cho client các trang HTML tương ứng.
**Phần thứ ba**
Mình hướng dẫn các bạn cách config cho web server biết thư mục chứa các tài nguyên tĩnh để server cho phép client tải về khi được yêu cầu.
### Express.js là gì ?
Express.js là một framework cung cấp cho chúng ta các tiện ích để định tuyến ( Routing ), xử lý các lớp trung gian (Middleware), Xử lý các yêu cầu và đáp ứng yêu cầu (HTTP Request và HTTP Resoponse) một cách dễ dàng hơn.
Qua bài học trước về cách xây dựng một HTTP server, thì các bạn đã hiểu được cách làm thế nào để có thể tạo một HTTP server, định tuyến và xử lý yêu cầu, đáp ứng yêu cầu. Thì giờ đây Express.js sẽ là một framework giúp bạn làm điều đó dễ dàng hơn. Tuy nhiên bản chất bên trong một framework làm gì thì nó vẫn bắt đầu từ những gì cơ bản nhất nhé.
### NPM là gì ?
NPM là một bộ công cụ quản lý thư viện của Node.js. Nó cho phép bạn có thể cài đặt và quản lý các thư viên , module một cách dễ dàng.
### Các cài đặt Express.js
Tại thư mục chứa ứng dụng sau khi đã chạy lệnh `npm init` để khởi tạo project thì các bạn gõ lệnh sau
`npm install express --save`
Đối số `--save` là để tự động lưu vào tệp tin package.json
Sau khi cài đặt xong thì các bạn có thể cùng mình bắt tay vào thực hành bài học được rồi.
## 4.2 Khởi tạo cấu trúc thư mục của ứng dụng
Đầu tiên từ thư mục gốc nơi các bạn khởi tạo ứng dụng, các bạn tao một cấu trúc thư mục như sau.
```markup
.
├── controllers
│ ├── core.server.controller.js
│ └── index.js
├── public
│ ├── css
│ ├── img
│ └── js
│ └── app.client.js
├── README.md
├── routes
│ ├── core.server.routes.js
│ └── index.js
├── server.js
└── views
├── contact.server.view.html
└── homepage.server.view.html
```
**Giải thích**
Thư mục **controllers** ở đây là để chứa các hàm xử lý tương ứng với mỗi route (path).
Thư mục **routes** là để chứa các file định tuyến cho cả ứng dụng.
Phong cách đặt tên file của mình là như trên, ví dụ `core.server.controller.js` thì nghĩa là mình hiểu đó là controller cho core module nằm ở phía server side. Đây là một best practice dành cho những ứng dụng có mã nguồn chứa cả khối client và server. Nó còn giúp bạn dễ dàng tìm kiếm file hơn.
mỗi thư mục đều có một file **index.js** đây là file chỉ mục của module, nó giúp exports tất cả các module con ra ngoài để dễ dàng require vào sử dụng.
## 4.1 Phần Controller
Trong bài học này controller đóng vai trò như là các handler tiếp nhận các yêu cầu thông qua router và giải quyết nó.
Mở file **core.server.controller.js** lên và gõ vào đó đoạn mã sau.
```javascript
"user strict";
// Module public methods.
module.exports = {
renderHomePage : renderHomePage,
renderContactPage : renderContact
};
/**
* @name renderHomePage
* @description
* Render homepage.
*
* @param {object} req HTTP request
* @param {object} res HTTP response
*/
function renderHomePage(req, res) {
res.send('This is homepage');
}
/**
* @name renderContact
* @description
* Render contact page.
*
* @param {object} req HTTP request
* @param {object} res HTTP response
*/
function renderContact(req, res) {
res.send('This is contact');
}
```
Trong file **src/controllers/index.js** thì bạn gõ vào đoạn mã sau
```javascript
const coreCtrl = require('./core.server.controller');
module.exports = {
Core : coreCtrl
};
```
Đơn giản là để export module core controller ra ngoài.
**Giải thích mã lệnh**
1) Thứ nhất bạn lưu ý req và res ở đây là Express HTTP request và Express HTTP response. Hai đối tượng này đã được Framework Express.js ghi đè lên đó một số phương thức nên cách sử dụng cũng khác với HTTP.IncommingMessage gốc của Node.js ở bài học trước.
2) Sau khi viết xong các function thì mình public nó ra bằng cách exports. Đây là một phong cách viết nên áp dụng vì nó rất rõ ràng để đọc. Chú ý khối exports được để ở đầu file, sẽ giúp người khác dễ đọc hơn, nắm bắt nhanh bên trong module có những function gì.
## 4.2 Phần Routing (Định tuyến)
Định tuyết là việc bạn chỉ định gắn một URL (Bao gồm path và method) đến một controller method cụ thể (Handle function)
mở file **core.server.routes.js** lên và gõ vào đoạn mã sau
```javascript
/**
* @module routes
* @description
* Define all core routes of applications
*/
"user strict";
const coreCtrl = require('../controllers').Core;
module.exports = function(app) {
app.route('/').get(coreCtrl.renderHomePage);
app.route('/contact').get(coreCtrl.renderContactPage);
};
```
Trong file **src/routes/index.js** thì bạn gõ vào đoạn mã sau.
```javascript
"user strict";
const coreRoutes = require('./core.server.routes');
module.exports = function(app) {
coreRoutes(app);
};
```
Trong phần mã này, để ý **app** ở đây chính là **express HTTP server**.
### 4.3 Phần Server
Mở file **server.js** lên và gõ vào đoạn mã sau
```javascript
"use strict";
const express = require('express');
const app = express();
const port = 3000;
// Do Registration routes.
require('./routes')(app);
app.listen(port, function(err) {
if(err) {
console.error('Something error !!');
console.error(err);
}
console.log('App listen on port ' + port);
});
```
**Giải thích mã lệnh**
Ta thấy rằng thay vì như bài học trước ta tạo một HTTP server bằng lệnh
```javascript
const http = require('http');
const server = http.createServer(requestHandler);
```
thì nay sẽ dùng Express để làm việc đó
```javascript
const express = require('express');
const app = express();
```
thứ hai, với express.js để định tuyến một đường dẫn thì ta sẽ làm như sau
```javascript
const express = require('express');
const app = express();
app.route('/').get(function handler(req, res) {
// Do somthing on request '/home' on 'GET' method
});
```
Như ví dụ trên, thì để code đẹp và gọn gàng hơn, ta tổ chức lại bằng cách truyền express http server **app** vào route module
```javascript
// Do Registration routes.
require('./routes')(app);
.............In /routes/index.js
module.exports = function(app) {
coreRoutes(app);
};
.............In /routes/core.server.routes.js
module.exports = function(app) {
app.route('/').get(coreCtrl.renderHomePage);
app.route('/contact').get(coreCtrl.renderContactPage);
};
```
Cách viết trên là một best practice để chia nhỏ module, giúp quản lý code dễ dàng hơn.
### 4.4 Khởi chạy ứng dụng
tại thư mục gốc của ứng dụng bạn chạy lệnh `node server` và nếu mọi thứ đều tốt bạn sẽ nhận được câu thông báo là
App listen on port 3000
sau đó mở trình duyệt lên và chạy thử đường dẫn 127.0.0.1:3000 và 127.0.0.1:3000/contact để xem kết quả nhé.
### 4.4 Thiết lập View Engine ( Hay còn gọi là template engine)
Đây là một công cụ hỗ trợ cho bạn hiển thị ra các trang HTML với nội dung động. Ví dụ bạn có một trang HTML với nội dung như sau
```markup
<p>{{content}}</p>
```
Thì bạn thấy rằng tương ứng với việc bạn truyền gì gì biến {{content}} mà trang HTML trả về cho người dùng sẽ có nội dung khác nhau. Để làm việc đó dễ dàng với Node.js mình sẽ sử dụng view engine.
>Nếu không sử dụng view engine thì theo bài học trước trong việc tạo một HTTP web server, các bạn phải sửdụng các phép nối chuỗi để làm điều này, với ứng dụng nhỏ thì không sao nhưng nếu ứng dụng lớn hơn thì sẽ rất là mệt và khó quản lý, đặc biệt là khi nội dung trang HTML cực kỳ phức tạp.
Ví dụ nếu không dùng view engine thì bạn sẽ phải làm một cái gì đó như sau. Chú ý mình viết trên ES6 để đỡ khổ , chứ ES5 thì ôi thôi rồi, toàn cộng chuỗi.
```javascript
/**
* @name renderHomePage
* @description
* Render homepage.
*
* @param {object} req HTTP request
* @param {object} res HTTP response
*/
function renderHomePage(req, res) {
let content = "This is dynamic page content for homepage !!!!!!";
return res.send(
`
<html>
<body>
<div class="header">
This is header
</div>
<div class="content">
${content}
</div>
</body>
</html>
`
);
}
```
### Giới thiệu template engine Handlebars.js
Sau một thời gian đổi nhiều template engine cho Sociss Class, đến nay mình đã chốt lại dùng Handlebars vì nó thật sự tuyệt vời, đơn giản, hiệu quả và mạnh mẽ.
Mình sẽ có riêng một bài học nâng cao cho phần này, tuy nhiên ở bài học này mình chỉ giới thiệu sơ qua các dùng cơ bản nhé.
### Thiết lập template engine
Đầu tiên các bạn cài đặt express-hbs, một bộ chuyển đổi hanlebard.js thành middleware để sử dụng kèm với express.js
từ thư mục gốc của project chạy lệnh
`npm install express-hbs --save`
Sau đó ban mở file **server.js** lên và chỉnh lại như sau
```javascript
"use strict";
const express = require('express');
const app = express();
const port = 3000;
let hbs = require('express-hbs');
// Do Registration routes.
require('./routes')(app);
// Set view template engine for file extension server.view.html
app.engine('server.view.html', hbs.express4({
extname: '.server.view.html'
}));
// Set view engine
app.set('view engine', 'server.view.html');
// Set views folder
app.set('views', './views');
app.listen(port, function(err) {
if(err) {
console.error('Something error !!');
console.error(err);
}
console.log('App listen on port ' + port);
});
```
Trong đó có thêm đoạn lệnh sau để đăng ký một template engine
```javascript
// Set view template engine for file extension server.view.html
app.engine('server.view.html', hbs.express4({
extname: '.server.view.html'
}));
// Set view engine
app.set('view engine', 'server.view.html');
// Set views folder
app.set('views', './views');
```
Trong đó lần lượt mình làm những điều sau.
1) Mình đăng ký với Express là mình có một template engine tên là 'server.view.html' . Làm vậy vì thực ra trong một website các bạn vẫn có thể sử dụng nhiều template engine cùng lúc chứ không chỉ riêng một cái.
2) Mình thiết lập cho express biết view engine mặc định là 'server.view.html'
3) Mình thiết lập thư mục chứa các file view cụ thể là thư mục chứa các file html.
Sau đó mở file **./controllers/core.server.controller.js** lên và chỉnh lại như sau.
```javascript
"user strict";
// Module public methods.
module.exports = {
renderHomePage : renderHomePage,
renderContactPage : renderContact
};
/**
* @name renderHomePage
* @description
* Render homepage.
*
* @param {object} req HTTP request
* @param {object} res HTTP response
*/
function renderHomePage(req, res) {
res.render('homepage', {
content : 'This is homepage content'
});
}
/**
* @name renderContact
* @description
* Render contact page.
*
* @param {object} req HTTP request
* @param {object} res HTTP response
*/
function renderContact(req, res) {
res.render('contact', {
content : 'This is contact page content'
});
}
```
**Giải thích**
res.render là một method trong HTTP response của Express, nó sẽ thực hiện việc render với view engine đã thiết lập.
Thứ hai mình chỉ ghi **homepage** nó sẽ tự hiểu vì là mình đã thiết lập thư mục chứa view file là './views' và định dạng tên mở rộng là '.server.view.html' nên nó sẽ tự hiểu
homepage --> ./views/homepage.server.view.html
Còn **content** là một biến chứa dữ liệu, trên trang view cụ thể mình sẽ gọi ra như sau. Mở file
**/views/homepage.server.view.html** lên và ghi vào đó nội dung đơn giản như sau
```markup
<b>{{content}}</b>
```
Cuối cùng ta lại chạy thử ứng dụng và mở trình duyệt lên kiểm tra nào.
### 4.5 Thiết lập tài nguyên tĩnh
Khi viết website thì hình ảnh, các file js, css thậm chí là các file văn bản khác có thể được xem là tài nguyên tĩnh. Tại sao lại cần phải khai báo tài nguyên tĩnh ?
Vì lý do bảo mật và an toàn cho server. Ví dụ trên server bạn có file .env, file này là file chứa toàn bộ các thiết lập database và mật khẩu truy xuất. Điều tồi tệ sẽ diễn ra nếu mọi người có thể truy cập nội dung này dễ dàng từ trình duyệt đúng không nào.
Chính vì vậy là mặc định mọi tài nguyên trên máy chủ đều bị ẩn, để cho truy xuất được bạn phải cấp quyền và chỉ rõ ra. Bước làm này chính là khai báo và thiết lập tài nguyên tĩnh.
Để làm điều này chỉ cần một dòng như sau là đủ
```javascript
app.use('/', express.static('./public'));
```
chèn dòng trên vào file **server.js** , khi ấy file này sẽ như sau
```javascript
"use strict";
const express = require('express');
const app = express();
const port = 3000;
let hbs = require('express-hbs');
// Do Registration routes.
require('./routes')(app);
// Set static content.
app.use('/', express.static('./public'));
......
```
**Giải thích ý nghĩa**
app.use('/', express.static('./public'));
Nghĩa là gắn đường dẫn '/' với thư mục ./public để cấp phát tài nguyên tĩnh. Sau đó ta thử tạo một file js ở đường dẫn './public/js/app.client.js'
khi ấy từ trình duyệt ta có thể gọi đến file trên qua đường dẫn
`http://127.0.0.1:3000/js/app.client.js`
Thử chỉnh lại là
app.use('/static', express.static('./public'));
khi ấy từ trình duyệt ta có thể gọi đến file trên qua đường dẫn
`http://127.0.0.1:3000/static/js/app.client.js`
Nào bước cuối cùng ta viết thử vào file **app.client.js** đoạn mã sau
```javascript
alert('Yeah !!!, you got me');
var x = document.getElementById("pTag");
x.innerHTML = "Content change by app.client.js !!!";
```
và sửa lại trong file **homepage.server.view.html** thành
```markup
<b>{{content}}</b>
<p id="pTag"></p>
<script src="/js/app.client.js"></script>
```
Và chạy lại ứng dụng, sau đó vào URL http://127.0.0.1:3000/ để xem kết quả. Nếu không có gì sai bạn sẽ nhận được một thông báo ( Có thể sẽ không hiển thị nếu bạn chặn mất thông báo từ thiết lập trình duyệt) và nội dung sẽ như thế này
This is homepage content
Content change by app.client.js !!!
## 5. Kết luận và nhận xét
Qua bài học này mình đã giới thiệu cho các bạn cách để tạo ra một website với Node.js. Về kiến trúc code thì nó đã tương đối tốt. Về nội dung bài học thì mình mong muốn các bạn hiểu về cách sử dụng cơ bản Express.js để làm việc, ý nghĩa của template engine và tài nguyên tĩnh (static content).
Ở bài học tiếp theo mình sẽ đi sâu hơn vào kiến trúc tổ chức một ứng dụng tốt hơn nữa, module hóa nhỏ hơn nữa. Và giải quyết các vấn đề về thiết lập môi trường chạy ứng dụng và chạy một Demo single page MVC đơn giản.
## 6. Bài tập
Mình có bài tập như sau, áp dụng các hướng dẫn trên, viết một website có hai trang là trang chủ và trang liên hệ có hình ảnh và css tương đối đẹp. Yêu cầu trong trang chủ bạn phải hiển thị được thông tin trình duyệt người dùng sử dụng.
**Gợi ý**
1) Bỏ hình ảnh vào thư mục img và gọi ra dùng tương tự cho css.
2) Lấy thuộc tính header 'user-agent' ra và hiển thị ra view thông qua template view engine.
Mã nguồn của bài học mình để ở Github theo link sau [Socis-blog-v1 Github](https://github.com/nghuuquyen/sociss-class-nodejs/tree/master/src/sociss-blog-v1)
# Tác giả
**Name:** <NAME> ( <NAME> )
**Email:** <EMAIL>
**Website:** [Sociss Class - Online Education Center](https://sociss.edu.vn/)
**Profile Page:** [<NAME> - Profile Page ](https://sociss.edu.vn/users/nghuuquyen)
<file_sep>/**
* @name Add
* @description
* Add two given number {a} and {b} .
*
* @param {number} a First number
* @param {number} b Second number
* @constructor
*/
module.exports.add = function Add(a, b) {
return a + b;
};
<file_sep>Chào các bạn đây là bài học đầu tiên của chúng ta với Git. Trong bài học này chúng
ta sẽ học bằng một câu chuyện kể về một nhóm gồm 3 bạn là Minh, Linh và Vũ (Team DevStory) có một dự án làm một trang web tính toán đơn giản bằng HTML và Javascript. Với bạn Minh là trưởng nhóm. Và câu chuyện bắt đầu.
Vào một ngày đẹp trời, sau khi cả ba đã thống nhất về ý tưởng xây dựng một ứng dụng
đơn giản với các tính năng yêu cầu trong Sprint 1 theo mô hình Scrum là
1) Thiết kế giao diện bằng PS
2) Tạo trang chủ ứng dụng
3) Có form nhập vào hai số và chọn phép tính sau đó tính toán và hiển thị
ra màn hình
Ở trên là hai product backlog, không thể để như vậy để làm mà phải phân rã thành
các task nhỏ hơn rồi estimate xem làm bao lâu, và thế các bạn ấy tách ra như sau
1) Thiết kế giao diện bằng PS (tổng 5)
+ Thiết kế trang chủ (3)
+ Thiết kế form nhập số để tính toán (2)
2) Tạo trang chủ ứng dụng (tổng 8)
+ Tải và cài đặt bootstrap (1)
+ Tạo header, footer (3)
+ khởi tạo layout trang chủ (2)
+ Hoàn thiện trang chủ với các thành phần đã có (2)
3) Có form nhập vào hai số và chọn phép tính sau đó tính toán và hiển thị
ra màn hình (tổng 7)
+ Tạo giao diện form bằng HTML với CSS của bootstrap (3)
+ Viết mã lệnh JS thực hiện tính toán và ghi lên form (2)
+ Gắn kết HTML với JS để hoàn thiện Form (2)
Sau khi gán xong số points cho mỗi backlog thì sẽ tiến hành quy đổi thành giờ làm
việc, nếu team quy ước một point là 1 giờ công thực tế thì Sprint 1 trên sẽ 15 points tương ứng với 15 giờ làm việc.
Xong, đến đây team thống nhất với việc phân rã task của mình, đến bước tiếp nhóm
trưởng Minh quyết định sẽ dùng Git để quản lý mã nguồn dự án, vì team có đến 3 người không thể dùng cách thử công được.
Nhóm trưởng Minh quyết định dùng một Cloud Git Server để cho cả Team dùng, tuy nhiên
lại phân vân giữa hai nhà cung cấp lớn là Github và Bitbucket.
Github hoàn toàn miễn phí nếu team chấp nhận public mã nguồn ra cho cộng đồng, ngược lại Bitbucket lại cho Team bí mật mã nguồn nhưng lại giới hạn ở mức 5 thành viên, trên đó là phải trả phí để mở rộng thành viên.
Suy nghĩ một hồi, nhóm trưởng Minh quyết định sử dụng Github cho project của Team mình.
Và thể là cậu ấy phải đi đến việc tạo một Remote repository trên Github.
# 1. Tạo mới một Repository trên Github
Sau khi đăng nhập vào Github thành công, chúng ta làm theo các bước như sau
1) Chọn vào menu user góc phải trên -> Profile
2) Tại trang profile chọn tab Repository
3) Nhấp vào nút **New**
Tại đây bạn điều vào tên project, nhớ điền ngắn gọn rõ nghĩa, điề n phần mô tả, chọn
kiểu public hay privite nếu public thì miễn phí , private thì sẽ bị trả phí.
Kế đến chọn mẫu .gitignore cho project, giả sử bạn viết bằng Java thì sẽ chọn Java, Github sẽ tự động add thêm file này vào project cho bạn.
Trong trường hợp Team DevStory thì dùng JS và HTML nên nhìn chung là ban đầu không
cần tệp tin này, Team sẽ tự add vào sau khi cần thiết.
Cuối cùng nhấp nút tạo, và bạn Minh đã có một remote repo trên Github cho team sử dụng.
Đường dẫn Repo sẽ là như sau
https://github.com/nghuuquyen/simple-calculator.git
Sau khi tạo xong repository trên Github, cậu ấy tiến hành khởi tạo cấu trúc Project
như sau.
```sh
.
└── simple-calculator
├── css
├── js
├── index.html
└── README.md
```
# 2. Khởi tạo Git cho một project đã tồn tại
Để khởi tạo Git cho một project, đầu tiên ta đi vào thư mục gốc project đó. Theo
trên chính là **simple-calculator**.
**Mở terminal lên hoặc CMD, từ đây mọi câu lệnh sẽ tương tác thông qua terminal hết nha**
Đầu tiên trong terminal, di chuyến đến thư mục gốc của project.
```sh
cd /simple-calculator
```
Sau khi đã ở trong thư mục gốc project, dùng lệnh sau
```sh
git init
```
Lúc này Git sẽ tự động tạo cho chúng ta thư mục .git để lưu trữ thông tin.
Nhưng vậy bạn Minh đã khởi tạo được Git thành công cho một project.
# 3. Kết nối Local repository với remote repository
Lúc này bạn Minh phải giải quyết vấn đề là kết nối local repo mà bạn ấy vừa khởi
tạo ở bước trên với remote repo đã tạo ở phần 1 trên Github. Đó gọi là thao tác
**add remote**
Đầu tiên chạy thử lệnh sau
```sh
git remote -v
```
và kết quả sẽ báo về là trống trơn vì chưa có remote repo nào cả. Sau đó ta tiến hành chạy lệnh sau để thêm mới một remote repo.
```sh
git remote add origin https://github.com/nghuuquyen/simple-calculator.git
```
Trong đó **origin** là tên của remote bạn đặt, origin là một tên chuẩn để chỉ remote gốc của project, sau này bạn có thể add thêm nhiều remote khác nếu muốn.
Kế đến là đường dẫn đến remote repo trên github mà bạn đã tạo trước đó.
Sau khi thực hiện xong lệnh trên thì bạn một lần nữa thử lệnh sau.
```sh
git remote -v
origin https://github.com/nghuuquyen/simple-calculator.git (fetch)
origin https://github.com/nghuuquyen/simple-calculator.git (push)
```
Như trên các bạn thấy rằng remote origin đã được chỉ định để fetch và push code.
Sau đó chúng ta tiến hành thực hiện commit đầu tiên để lưu trữ cấu trúc project đã tạo và đẩy lên Remote repo.
# 4. Kiểm tra trạng thái các tệp tin và nhánh hiện hành trước khi commit
Trước khi commit thì bạn cần kiêm tra xem tình trạng các file như thế nào.
Dùng lệnh `git status` để xem tình trạng file và nhánh hiện hành
```sh
git status
On branch master
Initial commit
Untracked files:
(use "git add <file>..." to include in what will be committed)
README.md
index.html
nothing added to commit but untracked files present (use "git add" to track)
```
Bạn thấy rằng có hai file là README.md và index.html đang bị trạng thái untracked.
Lúc này như bài học trước, bạn phải dùng lệnh `git add` để đẩy nó vào trạng thái
**staged**. Ta làm lân lượt từng lệnh như sau
```sh
git add README.md
git add index.html
```
Lúc này dùng lệnh `git status` một lần nữa để kiểm tra và ta thấy kết quả như sau
```sh
git status
On branch master
Initial commit
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: README.md
new file: index.html
```
Hai file mới đã vào trạng thái staged. Và là một file hoàn toàn mới. Ngoài ra bạn có thể kiểm tra branch hiện tại theo cách sau, dùng lệnh `git branch` nhưng nếu
trong lần đầu tiên bạn sẽ không thấy branch nào hết vì bạn đang dùng branch mặc định của Git là master.
# 5. Commit đầu tiên
Sau khi đã kiểm tra mọi thứ và add những file cần thiết vào trạng thái staged để sãn sàng commit thì bạn sẽ bắt đầu commit thử lần đầu tiên.
**Chú ý** : Mình nói những file cần thiết là vì những file không staged thì sẽ không được lưu vào repo khi ta commit.
Để commit ta dùng lệnh sau `git commit` cụ thể
```sh
git commit -m "Initial project struct"
[master (root-commit) d1a1956] Initial project struct
2 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 README.md
create mode 100644 index.html
```
Với chỉ định -m theo sau đó là một văn bản bỏ trong dấu nháy kép, đó chính là commit message, hay nói ngắn gọn commit này làm gì , có ý nghĩa gì.
để ý **d1a1956** chính là mã của commit này, sau này với mã này bạn có thể xem lại commit lần này tương tác hay thay đổi những file nào.
Sau đó ta thử dùng lệnh `git log` để xem lại lịch sử commit nào
```sh
git log
commit d1a1956b1c06ac95201726c9aa5a457db492cf01
Author: <NAME> <<EMAIL>>
Date: Sat Oct 21 14:31:41 2017 +0700
Initial project struct
```
Như trên ta thấy rõ mã commit, tên tác giả, ngày giờ và nội dung commit. Và đến đây
chúng ta đã commit thành công rồi.
tiếp theo đó là làm thế nào để đẩy mã nguồn của chúng ta lên remote git repo ở github
# 6. Đẩy mã nguồn từ một nhánh ở local repo lên remote repo
Đầu tiên trước khi đẩy, chúng ta phải hiểu là đẩy code, tức là đẩy mã nguồn từ một nhánh ở local lên một nhánh ở remote, thường thì đây là một nhánh tương ứng với nhánh ở local.
Trong lần này, chúng ta đang ở trên branch master ở local và muốn đẩy code lên nhánh master ở remote repo. Chúng ta dùng lệnh sau
```sh
git push origin master
```
Với origin chính là tên của remote repo chúng ta đã thêm vào ở bước trước. Và master là tên nhánh.
**Lưu ý** master tức là ngầm hiểu local branch và remote branch cùng tên. Trong trường hợp local branch khác tên với remote branch thì bạn phải chỉ rõ tên của local và remote branch bằng cách ghi là local-master:master. Đây là một kỹ thuật
khác mình sẽ có bài viết nâng cao nói về cài này. Thông thường bạn nên push code từ một nhánh local cùng tên là dễ hiểu nhất.
```sh
git push origin master
Username for 'https://github.com': nghuuquyen
Password for 'https://nghuuquyen@github.com':
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 242 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To https://github.com/nghuuquyen/simple-calculator.git
* [new branch] master -> master
```
Sau khi gõ lệnh bạn sẽ phải nhập username và password (Chú ý nó là ẩn không hiện lên nên bạn cứ gõ mật khẩu đúng vào và enter nhé).
để ý 2 dòng cuối, bạn sẽ thấy đường dẫn của remote repo và dòng cuối ghi là
đã tạo mới trên repo repo nhánh master mới, và ta đã push từ local master đến
remote master.
Lúc này mở github lên ở đường dẫn của remote repo và reload lại. Bạn sẽ thấy mã nguồn của mình đã ở trên github.
Cuối cùng để thử lấy tất cả các nhánh trên remote repo về, bạn dùng lệnh `git fetch`. và sau đó thử xem lệnh `git branch`
```sh
git fetch
git branch
* master
```
Và kết quả trả về là bạn đang ở trên nhánh master. Để kiểm tra tình trạng các nhánh ở local với master bạn dùng lệnh `git remote show origin`
```sh
git remote show origin
* remote origin
Fetch URL: https://github.com/nghuuquyen/simple-calculator.git
Push URL: https://github.com/nghuuquyen/simple-calculator.git
HEAD branch: master
Remote branch:
master tracked
Local ref configured for 'git push':
master pushes to master (up to date)
```
Kết quả trả về là sẽ liệt kê danh sách tất cả các remote và repo cho mỗi remote tương ứng, trong remote origin các bạn để ý là nhánh master ở local đã ghi là `up to date` nghĩa là đã là bản mới nhất so với nhánh master ở trên remote repo. Vậy là code trên nhanh của bạn đã là mới nhất rồi. Thường thì lệnh này để bạn có cái nhìn tổng quát về thay đổi ở tất cả các nháy nếu có để cập nhật code về.
Giả sử nếu có thay đổi bạn có thể cập nhật tất cả bằng lệnh `git fetch`.
# 7. Một bạn khác trong team tải mã nguồn về để làm việc
Sau khi xong bước trên, thì đến bước này bạn trưởng nhóm Minh, sẽ rút điện thoại ra nói mọi người là mình đã đẩy code lên github rồi, mọi người lên lấy về xem nhé.
Vậy làm sao để một bạn khác trong team lấy được mã nguồn về ?
Rất đơn giản, ta sẽ dùng lệnh `git clone`
Để giả lập việc này, bạn có thể tạo một thư mục nào đó ở ngoài thư mục **working directory** hiện tại của project mà bạn đang làm việc để thử việc clone.
Ví dụ mình tạo mới một thư mục là **test-clone-app** để giải sử cho việc minh đang ở một máy tính khác. Bạn vào thư mục mới tạo này, mở terminal lên và gõ vào đó lệnh sau.
```sh
git clone https://github.com/nghuuquyen/simple-calculator.git
```
Và kết quả là
```sh
Cloning into 'simple-calculator'...
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
```
Để ý ta thấy rằng theo sau lệnh git clone chính là URL của remote repo trên github.
Sau khi clone thành công thì bạn đã có source code của project mà trưởng nhóm Minh đã tạo để làm việc rồi. Toàn bộ source code của project sẽ ở trong thư mục
**/test-clone-app/simple-calculator**
# 8. Làm thể nào để một bạn khác trong Team có thể đẩy code lên remote repo
Mặc định ban đầu chỉ người tạo repo mới có thể tự do đẩy code lên repo mình tạo. Để một bạn khác có thể đẩy code của mình làm vào remote repo thì có hai cách.
1) Thêm bạn ấy vào danh sách người dùng được cấp phép đẩy code vào remote repo.
2) Bạn kia phải folk ra một repo khác và tự đẩy code lên repo của mình, sau đó tạo pull request về remote repo gốc.
Ở trên thì cách 2 là cách nâng cao, thường dùng cho các open source project để cộng đồng có thể đóng góp cho một project, mình sẽ bàn đến ở bài học khác. Ở bài này mình chọn cách dễ nhất đó là bạn Minh trưởng nhóm sẽ cấp quyền push code cho các member của mình là <NAME>.
Để có thể cấp quyền cho người dùng khác vào repo của mình trên github các bạn làm
như sau
1) Vào trang chủ repo của mình (Khi đã đăng nhập vào tài khoản tạo ra repo ấy).
2) Vào tab settings --> Mở thẻ Collaborators --> Nhập lại mật khẩu nếu bị yêu cầu
3) Điền vào ô username hoặc email của team member và nhấn vào nút add.
4) Gọi điện thoại nói team member đăng nhập email đã đăng ký với github để chấp thuận yêu cầu.
5) Sau khi member kia chấp thuận yêu cầu member đó đã có quyền đẩy code lên repo
Việc quản lý thành viên trong repo, bạn có thể quản lý trong settings/Collaborators
Tới đây là bạn đã cấp quyền thành công, giờ tiếp theo là chúng ta thử nghiệm đẩy code lên remote repo với tài khoản khác xem nào.
# 9. Làm việc với remote repo trên tài khỏan của thành viên (Collaborators)
Giờ chúng ta lại vào thư mục test-clone-app đã tạo ở trước để giả lập việc,làm việc
ở một máy tính của bạn khác, trên tài khỏa github của bạn ấy.
Giả sử ở đây là bạn Linh,
Đầu tiên vào lại thư mục test-clone-app và mở terminal lên. di chuyển đến thư mục project bằng lệnh `cd /simple-calculator`. Thử kiểm tra lệnh `git branch` nếu trả
về là master tức là bạn đã ở đúng thư mục project.
Lúc này bạn thử tạo một thư mục css và tạo file style.css ở thư mục đó
```sh
.
├── css
│ └── style.css
├── index.html
└── README.md
```
Cấu trúc thư mục sẽ như sau, Sau đó bạn sẽ dùng lệnh git add để đẩy file vào trạng thái staged.
```sh
git add css/style.css
```
Chú ý để add tất cả các file và thư mục đang được tracked hoặc những tệp tin mới tạo thì bạn có thể dùng lệnh `git add .`. Ở ví dụ của Minh, dù đã tạo thư mục css và js nhưng chưa add vào cho git biết nên lúc commit hai thư mục này sẽ không được thêm vào, đó là lý do là lúc này ở máy tính của bạn khác, ta clone về sẽ không thấy hai thư mục này.
Sau khi đã add thì ta commit code.
```sh
git commit -m "Create style.css for homepage"
[master 63e81ec] Create style.css for homepage
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 css/style.css
```
và cuối cùng là `git push` để đẩy code lên nhánh master ở remote repo trên github.
```sh
git push origin master
Username for 'https://github.com': sociss-education
Password for 'https://<EMAIL>':
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 351 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To https://github.com/nghuuquyen/simple-calculator.git
d1a1956..63e81ec master -> master
```
mình dùng lệnh `git push origin master`, và tài khoản mình dùng là **sociss-education** đay là tài khoản mà mình đã cấp quyền. Và như trên code đã được đẩy lên thành công từ tài khoản sociss-education.
Mở github lên và kiểm tra,lúc này chắc chắn bạn sẽ thấy cập nhật mới nhất có tệp tiên css/stylt.css
# 10. Thiết lập thông tin cá nhân chủ sở hữu cho local repo
Lúc này có một điều đặc biệt mà các bạn có thể thấy là nếu sử dụng lệch `git log`
bạn sẽ thấy lịch sử như sau.
```sh
git log
commit 63e81ec01f9cbf36c60bb69a8dc4deeb285e946e
Author: <NAME> <<EMAIL>>
Date: Sat Oct 21 15:42:51 2017 +0700
Create style.css for homepage
commit d1a1956b1c06ac95201726c9aa5a457db492cf01
Author: <NAME> <<EMAIL>>
Date: Sat Oct 21 14:31:41 2017 +0700
Initial project struct
```
Để ý commit mới nhất là **Create style.css for homepage** lại ghi là tác giả là
<NAME> <<EMAIL>> dùng cho mình đăng nhập và commit bằng tài
khoản **sociss-education**. Nguyên do là vì do **git config** của máy tính bạn đang cài mặc định tài khoản Git cho máy tính này là <NAME> và địa chỉ email là <EMAIL>
Để thay đổi thì bạn sẽ chạy lần lượt hai lệnh sau nhưng thay vào đó tên và email của bạn nhé.
```sh
git config --global user.name "<NAME>"
git config --global user.email <EMAIL>
```
Và khi đó mọi commit sau này sẽ lấy thông tin tác giả là theo thiết lập đó.
# Kết luận và nhận xét
Qua bài học này mình đã hướng dẫn được cho các bạn các nội dung sau
1) Cách tạo một repository trên github
2) Cách thực hành lệnh clone, commit, add, branch và push
3) Cách cấp quyền cho một tài khoản để đẩy code lên remote repo github
Trong bài học tiếp theo mình sẽ hướng dẫn cách làm việc trên các nhánh khác nhau để
thực hiện các task mà mình đã chia ra ở đầu bài. Các bài học này sẽ liên kết với nhau nhé.
# Bài tập về nhà
Hãy đọc theo nội dung bài học và thử tạo một repo riêng cho mình, và tìm hiểu trước
cách tạo nhánh và merge để chuẩn bị cho bài học sau.
# Tác giả
**Name:** <NAME> ( <NAME> )
**Email:** <EMAIL>
**Website:** [Sociss Class - Online Education Center](https://sociss.edu.vn/)
**Profile Page:** [Nguyen Huu Quyen - Profile Page ](https://sociss.edu.vn/users/nghuuquyen)
<file_sep># Branch - Tìm hiểu về các thao tác trên nhánh
# I. Giới thiệu
Bài học gồm hai phần.
Phần đầu gồm những kỹ thuật căn bản trên nhánh, phần thứ hai là hướng dẫn các kỹ thuật nâng cao trên nhánh. Nội dung hai phần như sau.
## Phần 1. Căn bản
1) Tạo mới.
2) Liệt kê danh sách các nhánh
3) Chuyển đổi qua lại giữa các branch
4) Chuyển đổi giữa branch nhưng bị yêu cầu commit code
5) So sánh thay đổi giữa các branch
6) Đẩy mã nguồn một local branch lên remote branch
7) Cập nhật local branch với thay đổi ở remote branch
8) Tạo mới nhánh tại một commit cụ thể
9) Xóa nhánh
10) Phục hồi branch sau đã xóa
11) Khôi phục lại local branch về trạng thái trước đó
## Phần 2: Nâng cao
1) Merge branch.
2) Xử lý xung đột trên branch khi merge.
3) Phục hồi trạng thái của branch nếu merge thất bại.
4) Phục hồi lại remote branch nếu phát hiện có lỗi trong commit đã push.
# Phần 1. Căn bản
# 1. Tạo mới một nhánh
Để tạo mới một nhánh đơn giản là dùng lệnh `git checkout`. Khi thực hiện lệnh này trên nhánh nào, thì nhánh mới sẽ giống hoàn toàn nhánh đó. Tham số -b trong lệnh checkout là để chỉ việc tạo mới một nhánh.

Ví dụ:
```sh
git checkout master
git checkout -b new_branch
```
Kết quả là new_branch sẽ có code và lịch sử giống hoàn toàn với master.
# 2. Liệt kê danh sách các nhánh
Để liệt kê danh sách các nhánh ta dùng lệnh `git branch`. Kết quả trả về là toàn bộ các nhánh có trong repo. Trong đó nhánh có dấu hoa thị `*` là nhánh hiện tại ta đang đứng.

Ví dụ:
```sh
git branch
dev
* master
```
Như trên là ta đang ở nhánh master.
# 3. Chuyển đổi qua lại giữa các branch
Để chuyển đổi qua lại giữa các nhánh, ta dùng lệnh `git checkout TÊN_NHÁNH`. Chú ý là không có tham số -b nhé.

Ví dụ
```sh
git checkout dev
Switched to branch 'dev'
git checkout master
Switched to branch 'master'
```
# 4. Chuyển đổi giữa branch nhưng bị yêu cầu commit code
Trong trường hợp bạn chuyển sang nhánh mới khi đang code dang dở, thì sẽ bị yêu cầu commit code, tuy nhiên không phải lúc nào bạn cũng muốn commit code cả. Có một cách là sẽ đẩy toàn bộ working tree hiện tại vào stash bằng lệnh `git stash`. Sau đó khi muốn lấy lại working tree đang làm thì dùng lệnh `git stash pop` để lấy ra.
```sh
git stash
git checkout dev
... Do something ....
... Done, and back to master ....
git checkout master
git stash pop
```
# 5. So sánh thay đổi giữa các branch
Nếu bạn muốn so sách các commit hoặc các file khác biệt giữa hai nhánh bất kỳ thì dùng lệnh `git diff`.

Ví dụ so sách master với dev
```sh
git diff master dev
```
Nếu chỉ muốn xem tên những file khác nhau ở hai nhánh thì dùng thêm tham số --name-only.
```sh
git diff master dev --name-only
```
# 6. Đẩy mã nguồn một local branch lên remote branch
Cái này đơn giản là ta checkout đến nhánh muốn đẩy, commit code xong rồi push lên remote origin thôi.
Ví dụ

```sh
git checkout master
git add data.txt
git commit -m "Update data.txt"
git push origin master
```
Code trên nhảy đến nhánh master sẽ đẩy lên nhánh master ở remote origin.
# 7. Cập nhật local branch với thay đổi ở remote branch
Khi hai người cùng làm việc trên một nhánh, việc người này phải cập nhật code mới của người kia là điều bình thường. Để làm việc này dùng lệnh `git pull`.

Ví dụ.
```sh
git pull origin master
```
Lệnh trên sẽ kéo code từ nhánh master trên remote repo về nhánh ở local hiện tại.
**Lưu ý**
1) Bạn có thể từ nhánh này pull code nhánh khác về, ví dụ pull code nhánh dev về master.
2) Bạn phải có thiết lập remote repo rồi thì mới pull được, dùng `git remote -v` để kiểm tra tên và URL của remote repo.
3) Lệnh `git pull` bên trong sẽ thực hiện hai lệnh `git fetch` và `git merge`
4) Lệnh `git pull` sẽ tự động **fast-forward** nếu có thể, nên nếu muốn luôn luôn tạo ra một merge commit để dễ quản lý và khôi phục thì nên dùng thêm đối số **--no-ff**. ví dụ
```sh
git pull origin master --no-ff
```
Lúc này bạn luôn phải nhập merge commit message cho lần pull đó.
**Ưu điểm** : Cái này tiện là sau này đọc log sẽ biết bạn pull code vào lúc nào, tránh trường hợp có quá nhiều commit con được merge vào gây khó quản lý và khôi phục khi có lỗi xảy ra.
**Nhược điểm**: Sẽ gom các commit con lại thành một, nên khi bị lỗi phải gỡ bỏ, thì phải gỡ luôn cả cục đi. Đôi khi phải gỡ đi cả những tính năng chạy được. Vì vậy nên khi commit và tạo pull request thì nên tạo theo một tính năng cụ thể, tránh hỗn hợp lộn xộn.
# 8. Tạo mới nhánh tại một commit cụ thể
Trường hợp bạn muốn tạo ra một nhánh có code tương ứng với một commit nào đó. Thì giải pháp là bạn sẽ tạo ra một nhánh mới với **HEAD trỏ tới commit hoặc một tag** cụ thể nào đó.
Ví dụ mình muốn nhánh quay về trạng thái ở commit có mã là **634ef682** thì lúc này mình muốn có một nhánh mới tên là **old-dev** với trạng thái code ở commit trên, thì làm như sau.

```sh
git checkout -b old-dev 634ef682
```
Sau đó bạn sẽ có một nhánh mới tên là **old-dev** có mã nguồn tương ứng với commit 634ef682.
**Ứng dụng** :
1) Quản lý phiên bản khi kết hợp với `git tag`. Ví dụ câu lệnh `git checkout -b release-v1.5.1 v1.5.1-stable` sẽ tạo ra nhánh release cho production tương ứng với phiên bản có tag là **v1.5.1-stable**.
2) Có thể ứng dụng trong việc debug lỗi để xem tại commit nào trên nhánh thì bị lỗi để có thể tạm thời quay về một commit nào đó gần nhất có thể dùng được.
3) Để đọc lại code cũ dễ dàng hơn, và còn nhiều ứng dụng khác tùy vào bạn ứng dụng ra sao.
Phần thao tác với Tag để quản lý phiên bản và mô hình phân nhánh tiêu chuẩn cho Git mình sẽ viết ở bài học khác.
# 9. Xóa nhánh
Để xóa một nhánh thì đơn giản là bạn dùng câu lệnh `git branch -d TÊN_NHÁNH` để xóa một nhánh bất kỳ.

ví dụ
```sh
git branch -d dev
```
Câu lệnh trên sẽ xóa nhánh dev nếu thỏa hai điều trên. Trong đó tham số -d (viết thường) là ám chỉ việc chỉ xóa nhánh khi nhánh đó đã đồng bộ với nhánh trên upstream tương ứng hoặc đã merge thành công vào HEAD hiện tại. **Nếu bạn muốn xóa dev bằng mọi giá** thì hãy dùng chữ -D (D hoa) thì Git sẽ xóa nhánh bất chấp bất cứ điều gì xảy ra.
**Lý thuyết sâu hơn** :
**1) Tại sao khi dùng -d lại phải thỏa điều kiện đồng bộ với nhánh trên upstream tương ứng hoặc merge thành công vào HEAD hiện tại ?**
-> Trả lời câu hỏi thứ nhất, đơn giản là vì Git không muốn bạn bị mất mã nguồn trên nhánh bị xóa, nên nó mới đòi hỏi bạn phải merge nhánh đó vào đâu đó hoặc push code lên nhánh upstream tương ứng trên remote repo đã.
**2) Khi nào nên dùng -D ?**
-> Khi bạn biết chắc chắn code trên nhánh bạn muốn xóa không có giá trị gì hết, nên không cần thiết phải đồng bộ lên remote hay merge gì cả. Thường là nhánh tạo ra để thử nghiệm cái gì đó thôi, xong rồi thì xóa đi.
# 10. Phục hồi branch sau khi đã xóa
Việc lỡ tay hay do nhầm lẫn mà xóa một branch là chuyện bình thường, trong trường hợp này vẫn có thể cứu được nếu còn reflog. Các bước như sau
**Video hướng dẫn**
**Bước 1: mở lịch sử reflog**
```sh
git reflog
```
**Bước 2: Tìm commit gần nhất có lịch sử liên quan đến nhánh bị xóa**
```sh
nghuuquyen:basic-operations$ git reflog
cbc2046 HEAD@{0}: checkout: moving from master to old-master
5493f45 HEAD@{1}: checkout: moving from old-master to master
```
Giả sử mình xóa mất nhánh **old-master** , đọc trong reflog từ trên xuống dưới thì thấy ở commit **cbc2046** có message là **checkout: moving from master to old-master** nghĩa là chuyển từ nhánh master sang old-master, như vậy **tại thời điểm commit cbc2046** nhánh old-master vẫn còn nguyên vẹn.
Nên ta sẽ khôi phục lại nhánh old-master bằng commit **cbc2046**
**Bước 3 : Phục hồi nhánh bằng cách checkout đến commit đã chọn**
Lúc này chúng ta sẽ checkout ra một nhánh mới với tên là old-master đến commit đã chọn ở bước hai, nhánh old-master sẽ được khôi phục nguyên vẹn.
```sh
git checkout -b old-master cbc2046
```
# 11. Khôi phục lại local branch về trạng thái trước đó
**Video hướng dẫn**
Đây là trường hợp khi bạn làm một thời gian, thì thấy các commit gần đây hoàn toàn sai lầm, và muốn xóa bỏ hết tất và quay lại một trạng thái commit trước đó trong trường hợp là các **commit lỗi này chưa đươc đẩy lên remote repo**. Thì bạn sẽ dùng `git reset` theo các bước sau.
**Bước 1** Xác định commit mà mình muốn quay về.
**Bước 2** Dùng lệnh git reset với tham số là commit ID được chọn.
Bước này dùng lệnh `git reset [commit_ID]` cộng với một trong ba đối số dưới đây
1) **--sort** : Sẽ giữ lại cả index(của commit đích) và working tree hiện tại. Hay nói đơn giản là nó quay lại trạng thái mà commit đó chưa được tạo (bạn chỉ mới add và staging area thôi).
2) **--mixed**: Sẽ xóa bỏ index (Hay staging area của commit đích) còn working tree hiện tại sẽ còn nguyên. Hay nói đơn giản hơn nó sẽ nhảy đến trạng thái commit đã tạo và HEAD đã trỏ đến commit đó.
3) **--hard** : Sẽ xóa bỏ cả index và cả working tree hiện tại. Hay nói đơn giản hơn là không lưu luyến gì cả, HEAD lúc này sẽ trở đến commit được chọn và working tree sẽ trống trơn.
```sh
git checkout dev
git reset 8062f9 --hard
```
Với câu lệnh trên, nhánh dev sẽ quay ngược về đúng trạng thái code sau khi đã thực hiện commit với ID là 8062f9.
# Phần 2. Nâng cao
# 1. Merge branch
Cái này áp dụng khi bạn checkout ra một branch mới để làm một tính năng, sau khi làm xong thì bạn sẽ nhập tính năng đó về lại nhánh chính.
Trong phần 1 này mình giả sử không có xung đột nào hết, thì bạn làm như sau

**Bước 1**: Di chuyển đến nhánh cần đích cần merge code từ nhánh tính năng vào
Ví dụ bạn đang ở nhánh feature-homepage để làm trang chủ, và đã xong. Lúc này bạn muốn merge code về nhánh master thì bạn sẽ checkout về nhánh master.
```sh
git checkout master
```
**Bước 2**: Chạy lệnh git merge
Giả sử như trên là bạn muốn merge nhánh feature-homepage vào master thì từ nhánh master bạn chạy lệnh sau
```sh
git merge feature-homepage
```
Và lúc này màn hình Vim đòi bạn nhập message cho lần merge sẽ nhập lên, bạn có thể chỉnh sửa hoặc tắt đi bằng Ctrl + x thì nó sẽ tự để mặc định. Và việc merge đã hoàn thành.
# 2. Xử lý xung đột trên branch khi merge.
Khi cả hai nhánh đều cùng chỉnh sửa một tệp tin nào đó, thì lúc merge với nhau sẽ gây xung đột.
**Video hướng dẫn**
## 2.1 Tạo ra xung đột
Đầu tiên chúng ta sẽ **thử thực hành tạo ra một xung đột giữa hai nhánh** theo các bước sau.
**Bước 1:** Tạo ra một tệp tin data.txt trên nhánh master, sau đó add và commit
```sh
git checkout master
git add data.txt
git commit -m "Create data.txt file"
```
**Bước 2:** Từ nhánh master, tạo ra một nhánh mới là dev
```sh
git checkout -b dev
```
**Bước 3:** Tại nhánh dev, chỉnh sửa file data.txt, sau đó commit và checkout về master lại
```sh
... Do change content file data.txt ...
git add data.txt
git commit -m "Change data.txt on dev"
git checkout master
```
**Bước 4:** Tại nhánh master cũng chỉnh sửa file data.txt, sau đó commit.
```sh
... Do change content file data.txt ...
git add data.txt
git commit -m "Change data.txt on master"
```
Sau bước 4 nhánh master và nhánh dev đã cùng chỉnh sửa một file là data.txt. Và đó là nguyên nhân gây ra xung đột
**Bước 5:** Tại nhánh master chạy lệnh merge nhánh dev vào, và lúc này sẽ thấy báo xung đột.
```sh
git merge dev
Auto-merging data.txt
CONFLICT (content): Merge conflict in data.txt
Automatic merge failed; fix conflicts and then commit the result.
```
Kết quả trả về là xung đột file data.txt
**Bước 6:** Ở nhánh master, chạy lệnh `git status -s`
```sh
git status -s
UU data.txt
```
Lúc này sẽ thấy file data.txt có trạng thái là **UU**
Trong đó:
U = updated but unmerged ( Cập nhật mà không merge được)
Nên UU nghĩa là : unmerged, both modified ( Cả hai đều cập nhật và không merge được)
## 2.2 Giải quyết xung đột
Tiếp theo, chúng ta **tiến hành giải quyết xung đột như sau**.
**Bước 1**: Chạy lệnh `git status -s`, tìm những file có trạng thái là UU. Đó là những file cần xử lý
**Bước 2**: Lần lượt mở từng file có trạng thái UU lên để chỉnh lại mã cho đúng .
Bước này gọi là xử lý xung đột, ví dụ như file data.txt ở trên có thể có nội dung như dưới đây.
```
<<<<<<<> HEAD
change on master
=======
Change on dev
>>>>>>> dev
```
Như trên nghĩa là phần nội dung ở phía trên là nội dung hiện tại ở HEAD (Chỉ nhánh master), còn phần nội dung bên dưới là phần ở nhánh dev.
Cách xử là là tùy ở bạn, ví dụ với mình thì mình thấy chỉ cần giữ lại cả hai dòng là xong. Như mình bên dưới là đã xử lý xong, nhớ xóa bỏ hết tất cả các ký tự đặc biệt của Git đi nhé.
```sh
change on master
Change on dev
```
Lưu lại file data.txt
**Bước 3**: Sau khi đã chỉnh sửa xong hết các file bị xung đột thì add và commit.
```sh
git add .
git commit -m "Merge branch 'dev'"
```
Lúc này đã giải quyết xung đột xong và merge hoàn tất.
# 3.Phục hồi trạng thái của branch nếu merge thất bại.
Sẽ có lúc bạn bị xung đột nhưng không thể giải quyết được ngay lúc đó, hoặc bạn không thể giải quyết mà đã lỡ gọi lệnh merge, thì để khôi phục lại trạng thái ban đầu rất đơn giản. Dùng lệnh `git merge --abort` hoặc lệnh `git reset` đều được.
Lệnh này sẽ quay về trạng thái trước khi thực hiện lệnh merge, nó sẽ clean toàn bộ index và working tree (**nên dùng**).
```sh
git merge --abort
```

Còn rệnh `git reset HEAD --hard` sẽ khôi phục hoàn toàn mã nguồn về trạng thái ban đầu của HEAD (Nếu dùng cái này thì bạn nên kiểm tra xem hiện tại HEAD đang ở đâu bằng `git log` cho an toàn nhé).
```sh
git reset --hard
```
**Lưu ý** : Mình dùng --hard vì mình biết rằng, trước khi bạn merge code thì nếu working tree không Clean (rỗng) thì Git đã ép bạn commit hoặc đẩy vào stash trước rồi. Nên dùng --hard để clean sạch index và working tree sinh ra trong lúc merge thất bại là hợp lý nhất.
# 4. Phục hồi lại remote branch nếu phát hiện có lỗi trong commit đã push.
Đây là một trường hợp mà khi bạn đã lỡ push code lên remote repo mà lại phát hiện ra lỗi. Lúc này sẽ có hai trường hợp.
1) Chưa có ai pull, push code hoặc nhánh remote đó chỉ của riêng bạn dùng.
2) Đã có ai đó pull code hoặc push code lên nhánh ấy.
## 4.1 Trường hợp chưa có ai pull, push code hoặc nhánh remote đó chỉ của riêng bạn dùng
Trong trường hợp này có hai cách giải quyết.
**Cách 1: Ghi đè để khôi phục lại nhánh remote (Nguy hiểm)**
**Bước 1** : Lưu working tree hiện tại nếu có bằng cách commit hoặc git stash.
**Bước 2** : Trên nhánh bị lỗi, khôi phục lại code đến commit không bị lỗi bằng `git reset --hard`
Mở log hoặc reflog tìm lại đến commit không bị lỗi, giả dụ là **A**. Thì lúc này bạn sẽ reset nhánh về commit đó bằng lệnh sau.
```sh
git reset --hard A
```
Thay A bằng commit ID bạn chọn. Ví dụ như hình.

**Bước 3** : Tiến hành push lên nhánh trên origin với tham số `-f`
```sh
git push orgin [branch_name] -f
```
Lệnh push với tham số `-f` là rất nguy hiểm, nó có nghĩa là ghi đè nội dung, bất chấp điều gì xảy ra. Nhờ vào sự ghi đè bất chấp này mà nhánh trên remote sẽ được khôi phục lại như ban đầu.
Tới đây thì đã cứu xong remote branch, nhưng ở local branch bạn lại đối mặt với việc là HEAD của bạn đã nhảy lùi về nhiều commit trước đó. Nên ở dưới local bạn lại phải một lần nữa dựa vào reflog để khôi phục lại trạng thái của branch bị lỗi trước đó để chỉnh sửa lại cho phù hợp rồi push lên lại. Khá là vất vả đó.
**Cách 2: Bạn sửa lỗi xong rồi đẩy lên nhánh lại**
Cách này thì rất bình thường, bạn cứ ung dung fix lỗi rồi đẩy lên lại, vì nếu nhánh đó của riêng bạn thì hoàn toàn không có vấn đề gì cả. Tuy nhiên phải để ý về thời gian, tránh người khác pull về rồi lại lây lan bug ra.
**Bước 1** : Pull lại code từ nhánh trên remote để chắc chắn là mới nhất
**Bước 2**: Sửa lại lỗi bạn gây ra và commit
**Bước 3**: Push code lên lại , lúc này push **không cần tham số -f** nhé.
## 4.2 Đã có ai đó pull code hoặc push code lên nhánh ấy
Trong trường hợp này có hai cách giải quyết,
**Cách 1: Bạn sửa lỗi xong rồi đẩy lên nhánh lại nhưng phải đăng thông báo ngay cho mọi người**
Đăng thông báo để tránh gây lây lan bug rồi lo fix thật nhanh để team khỏi phải chờ :D.
**Cách 2: Bạn sẽ thu hồi lại commit lỗi bằng lệnh revert**
**Video hướng dẫn**
Cách hai bạn sẽ dùng lệnh `git revert` để thu hồi commit, đây là cách phổ biến nhất và được khuyến khích dùng. Bản chất là nó tạo ra một revert commit làm ngược lại những thay đổi của commit bị lỗi để thu hồi lại chính commit đó (Nôm na là nếu bạn ghi vào một dòng gây lỗi thì đơn giản làm ngược lại là xóa dòng đó đi là xong). cách thực hiện rất đơn giản
**Bước 1** : dùng git log hoặc git reflog để tìm lại commit gây lỗi, bạn phải xác định được commit nào gây lỗi.
**Bước 2** : Chạy lệnh thu hồi commit gây lỗi đó
ví dụ 6058faa là commit gây lỗi, thì ta chạy lệnh sau
```sh
git revert 6058faa
```
**Bước 3**: Giải quyết xung đội nếu có và add các file bi xung đột đã giải quyết.
**Bước 3'**: Nếu có xung đột ở bước 3, thì sau khi giải quyết xong chạy lệnh `git revert --continue` để hoàn tất việc giải quyết xung đột. **Nếu không có xung đột** Git tự động bỏ qua bước này.
**Bước 4** : Nhập revert commit message nói vì sao bạn lại gỡ bỏ commit này và lưu lại
Thường bước này nó hiển thị trong Vim, nên nhấn `ctrl + o` để lưu rồi `ctrl + x` để thoát và hoàn tất nhé.
Tới đây là xong rồi, bạn có thể push lại lên nhánh remote kia, mọi người cũng sẽ pull về bình thường :D.
# Nhận xét và kết luận
Sau bài học này mình đã giới thiệu đến mọi người các kỹ thuật Git hay dùng trên một nhánh, hiểu các kỹ thuật này sẽ giúp bạn làm việc với Git thuận tiện và chuyên nghiệp hơn.
Ở bài học tiếp theo, chúng ta sẽ học về Git Rebase và các kỹ thuật thao tác trên Commit.
# Tác giả
**Name:** <NAME> ( <NAME> )
**Email:** <EMAIL>
**Website:** [Sociss Class - Online Education Center](https://sociss.edu.vn/)
**Profile Page:** [Nguyen Huu Quyen - Profile Page ](https://sociss.edu.vn/users/nghuuquyen)
|
89322a83436d8616829782044cb99a3affcf056f
|
[
"Markdown",
"JavaScript"
] | 45
|
Markdown
|
nghuuquyen/sociss-class-nodejs
|
e5424f8a4d4dca18e4078c09307f8ff46b3536fb
|
4cc0470b76b746cee87eb0bdee7233838223f9d4
|
refs/heads/master
|
<file_sep>import { Component } from '@angular/core';
import { NavController} from 'ionic-angular';
import { AuthService } from '../../providers/technical/auth-service';
import { LoginPage } from '../login/login';
@Component({
selector: 'page-logout',
template: ''
})
export class LogoutPage {
constructor(public navCtrl: NavController, public authService: AuthService) {
this.authService.logout();
this.navCtrl.setRoot(LoginPage);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Http, Headers, ConnectionBackend, Request, RequestOptions, RequestOptionsArgs, Response } from '@angular/http';
import { Storage } from '@ionic/storage';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import * as io from 'socket.io-client';
/**
* Custom Http Service for token and server address
*
* @export
* @class HttpService
* @extends {Http}
*/
@Injectable()
export class HttpService extends Http {
private _apiUrl;
private _token;
/**
* Creates an instance of HttpService.
* @param {ConnectionBackend} backend
* @param {RequestOptions} defaultOptions
* @param {Storage} storage
*
* @memberOf HttpService
*/
constructor(public backend: ConnectionBackend, public defaultOptions: RequestOptions, public storage: Storage) {
super(backend, defaultOptions);
}
/**
* Init the HttpService with datas from storage
*
* @param {any} cb
*
* @memberOf HttpService
*/
init(cb) {
Observable.forkJoin([this.storage.get('apiUrl'), this.storage.get('token')])
.subscribe((datas) => {
this._apiUrl = datas[0];
this._token = datas[1];
cb();
});
}
/**
* Injection of token and apiUrl
*
* @param {(string|Request)} url
* @param {RequestOptionsArgs} [options]
* @returns {Observable<Response>}
*
* @memberOf HttpService
*/
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
if (this._apiUrl !== undefined) {
if (typeof url === 'string') {
if (!options) {
options = {headers: new Headers()};
}
if (this._token) {
options.headers.set('Authorization', `Bearer ${this._token}`);
}
url = this._apiUrl + url;
} else {
if (this._token) {
url.headers.set('Authorization', `Bearer ${this._token}`);
}
url.url = this._apiUrl + url.url;
}
return super.request(url, options).timeout(3000);
}
else {
console.log("no apiUrl");
return null;
}
}
/**
* Change apiUrl
*
* @param {any} newApiUrl
*
* @memberOf HttpService
*/
set apiUrl(newApiUrl: any) {
// Check if api url is correct
if (newApiUrl !== undefined && newApiUrl !== null && newApiUrl !== this._apiUrl) {
if (!newApiUrl.startsWith('http://') && !newApiUrl.startsWith('https://')) {
newApiUrl = 'http://' + newApiUrl;
}
this.storage.set('apiUrl', newApiUrl);
this._apiUrl = newApiUrl;
}
}
/**
* Get ApiUrl
*
* @returns {String}
*
* @memberOf HttpService
*/
get apiUrl(): any {
return this._apiUrl;
}
set token(newToken: any) {
this._token = newToken;
}
get socket(): any {
return io(this._apiUrl, {
ws: true,
query: 'token=' + this._token
});
}
}
<file_sep>import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[temp-color]' // Attribute selector
})
export class TempColor {
@Input('temp-color') set temperature(temp) {
this.el.nativeElement.style.backgroundColor = '#f6f6f6'
};
constructor(public el: ElementRef) {
if (this.temperature !== undefined) {
this.el.nativeElement.style.backgroundColor = '#f6f6f6';
}
}
}
<file_sep>import { Component, ViewChild } from '@angular/core';
import { Nav, Platform, LoadingController } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { LoginPage } from '../pages/login/login';
import { WeatherPage } from '../pages/weather/weather';
import { LogoutPage } from '../pages/logout/logout';
import { HttpService } from '../providers/technical/http-service';
import { AuthService } from '../providers/technical/auth-service';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
@ViewChild(Nav) nav: Nav;
private rootPage: any;
private pages: Array<{title: string, component: any}>;
private loading: any;
constructor(public platform: Platform, public loadingCtrl: LoadingController, public authService: AuthService, public http: HttpService) {
this.initializeApp(platform);
this.pages = [
{
title: 'Météo',
component: WeatherPage
},
{
title: 'Déconnexion',
component: LogoutPage
}
];
}
openPage(page) {
this.nav.setRoot(page.component);
}
initializeApp(platform) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
this.showLoader();
this.http.init(() => {
this.authService.checkAuthentification()
.then(res => {
this.loading.dismiss();
this.rootPage = WeatherPage;
}, err => {
this.loading.dismiss();
this.rootPage = LoginPage;
});
});
});
}
showLoader(){
this.loading = this.loadingCtrl.create({
content: 'Connexion en cours...'
});
this.loading.present();
}
ready
}
<file_sep>import { Component, OnDestroy } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { WeathersService } from '../../../providers/datas/weathers-service';
@Component({
selector: 'page-pressure',
templateUrl: 'pressure.html'
})
export class PressurePage implements OnDestroy {
public pressure: any;
public extreme: any;
/**
* Creates an instance of PressurePage.
* @param {NavController} navCtrl
* @param {NavParams} navParams
*
* @memberOf PressurePage
*/
constructor(public navCtrl: NavController, public navParams: NavParams, public weathersService: WeathersService) {
this.weathersService.getLastPressure()
.subscribe(data => {
this.pressure = data
});
this.weathersService.joinRoom('weather');
this.weathersService.getUpdates('pressure', ':save')
.subscribe(data => {
if (data.type === 'indoorTemp') {
this.pressure = data;
if (this.pressure.value < this.extreme.min.value) {
this.extreme.min.value = this.pressure.value;
this.extreme.min.date = new Date();
}
if (this.pressure.value > this.extreme.max.value) {
this.extreme.max.value = this.pressure.value;
this.extreme.max.date = new Date();
}
}
});
this.weathersService.getExtremePressure()
.subscribe(data => {
this.extreme = data;
});
}
/**
* formattedPressure
*
* @readonly
*
* @memberOf PressurePage
*/
get formattedPressure() {
var retour = "";
if (this.pressure !== undefined && this.pressure.value !== undefined) {
retour = this.pressure.value.toString() + ' hPa';
}
return retour;
}
/**
* Leave socket room on Destroy
*/
ngOnDestroy() {
this.weathersService.leaveRoom('weather');
}
}<file_sep>import { Injectable } from '@angular/core';
import { HttpService } from '../technical/http-service';
import 'rxjs/add/operator/map';
/**
* Get Users datas
*
* @export
* @class UsersService
*/
@Injectable()
export class UsersService {
/**
* Creates an instance of UsersService.
* @param {HttpService} http
*
* @memberOf UsersService
*/
constructor(public http: HttpService) {
}
/**
* Check if user is authenticated on server
*
* @returns
*
* @memberOf UsersService
*/
me() {
return this.http.get('/api/users/me');
}
}
<file_sep>import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { IndoorTempPage } from './temperature/indoorTemp';
import { OutdoorTempPage } from './temperature/outdoorTemp';
import { PressurePage } from './pressure/pressure';
@Component({
selector: 'page-weather',
templateUrl: 'weather.html'
})
export class WeatherPage {
public indoorTemp = IndoorTempPage;
public outdoorTemp = OutdoorTempPage;
public pressure = PressurePage;
public weathers: any;
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpService } from '../technical/http-service';
import { DatasService } from '../technical/datas-service';
import 'rxjs/add/operator/map';
/**
* Get Weathers datas
*
* @export
* @class WeathersService
*/
@Injectable()
export class WeathersService extends DatasService {
/**
* Creates an instance of WeathersService.
* @param {HttpService} http
*
* @memberOf WeathersService
*/
constructor(public http: HttpService) {
super(http);
}
/**
* Get datas between 2 dates
*
* @param {Number} start
* @param {Number} end
* @returns
*
* @memberOf WeathersService
*/
get(start: Number, end: Number) {
return this.http.get('/api/weathers/' + start + '/' + end)
.map(this.extractData)
.catch(this.handleError);
}
/**
* getLastIndoorTemp
*
* @returns
*
* @memberOf WeathersService
*/
getLastIndoorTemp() {
return this.http.get('/api/weathers/indoorTemp/last')
.map(this.extractData)
.catch(this.handleError);
}
/**
* getExtremeIndoorTemp
*
* @returns
*
* @memberOf WeathersService
*/
getExtremeIndoorTemp() {
return this.http.get('/api/weathers/indoorTemp/' + this.getExtremeUrl())
.map(this.extractData)
.catch(this.handleError);
}
/**
* getLastOutdoorTemp
*
* @returns
*
* @memberOf WeathersService
*/
getLastOutdoorTemp() {
return this.http.get('/api/weathers/outdoorTemp/last')
.map(this.extractData)
.catch(this.handleError);
}
/**
* getExtremeOutdoorTemp
*
* @returns
*
* @memberOf WeathersService
*/
getExtremeOutdoorTemp() {
return this.http.get('/api/weathers/outdoorTemp/' + this.getExtremeUrl())
.map(this.extractData)
.catch(this.handleError);
}
/**
* getLastPressure
*
* @returns
*
* @memberOf WeathersService
*/
getLastPressure() {
return this.http.get('/api/weathers/pressure/last')
.map(this.extractData)
.catch(this.handleError);
}
/**
* getExtremePressure
*
* @returns
*
* @memberOf WeathersService
*/
getExtremePressure() {
return this.http.get('/api/weathers/pressure/' + this.getExtremeUrl())
.map(this.extractData)
.catch(this.handleError);
}
/**
* getExtremeUrl
*
* @private
* @returns
*
* @memberOf WeathersService
*/
private getExtremeUrl(): String {
return new Date().setHours(0,0,0,0) + '/' + new Date().getTime() + '/extreme';
}
}
<file_sep>import { NgModule, ErrorHandler } from '@angular/core';
import { XHRBackend, RequestOptions } from '@angular/http';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { Storage } from '@ionic/storage';
// Pages
import { LoginPage } from '../pages/login/login';
import { LogoutPage } from '../pages/logout/logout';
import { WeatherPage } from '../pages/weather/weather';
import { IndoorTempPage } from '../pages/weather/temperature/indoorTemp';
import { OutdoorTempPage } from '../pages/weather/temperature/outdoorTemp';
import { PressurePage } from '../pages/weather/pressure/pressure';
// Providers
import { HttpService } from '../providers/technical/http-service';
import { AuthService } from '../providers/technical/auth-service';
import { UsersService } from '../providers/datas/users-service';
import { WeathersService } from '../providers/datas/weathers-service';
// Directives
import { TempColor } from '../components/temp-color';
@NgModule({
declarations: [
MyApp,
LoginPage,
WeatherPage,
LogoutPage,
IndoorTempPage,
OutdoorTempPage,
PressurePage,
TempColor
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
LoginPage,
WeatherPage,
LogoutPage,
IndoorTempPage,
OutdoorTempPage,
PressurePage
],
providers: [
{
provide: ErrorHandler,
useClass: IonicErrorHandler
},
Storage,
{
provide: HttpService,
useFactory: (backend: XHRBackend, options: RequestOptions, storage: Storage) => {
return new HttpService(backend, options, storage);
},
deps: [XHRBackend, RequestOptions, Storage]
},
AuthService,
UsersService,
WeathersService
]
})
export class AppModule {}
<file_sep>import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MenuController, NavController, LoadingController } from 'ionic-angular';
import { WeatherPage } from '../weather/weather';
import { AuthService } from '../../providers/technical/auth-service';
import { HttpService } from '../../providers/technical/http-service';
@Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
public loading: any;
public loginForm: FormGroup;
public loginError: String;
constructor(public menu: MenuController, public navCtrl: NavController, public loadingCtrl: LoadingController, public authService: AuthService, public http: HttpService, public formBuilder: FormBuilder) {
this.loginForm = formBuilder.group({
server: [this.http.apiUrl, Validators.required],
email: ['', Validators.compose([Validators.pattern('^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$'), Validators.required])],
password: ['', Validators.required]
});
this.menu.enable(false);
}
login() {
this.showLoader();
this.loginError = '';
this.authService.login(this.loginForm.value)
.then(result => {
this.loading.dismiss();
this.menu.enable(true);
this.navCtrl.setRoot(WeatherPage);
}, err => {
if (err.message && err.message !== 'timeout') {
this.loginError = err.message;
}
else {
this.loginError = 'Impossible de se connecter au serveur. Veuillez vérifier l\'URL d\'accès.';
}
this.loading.dismiss();
});
}
showLoader(){
this.loading = this.loadingCtrl.create({
content: 'Connexion en cours...'
});
this.loading.present();
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpService } from './http-service';
import { Storage } from '@ionic/storage';
import { UsersService } from '../datas/users-service';
import 'rxjs/add/operator/map';
/**
* Authentication service
*
* @export
* @class AuthService
*/
@Injectable()
export class AuthService {
/**
* Creates an instance of Auth.
* @param {HttpService} http
* @param {Storage} storage
* @param {User} user
*
* @memberOf Auth
*/
constructor(public http: HttpService, public storage: Storage, public usersService: UsersService) {
}
/**
* Check is user is authenticated
*
* @returns Promise
*
* @memberOf Auth
*/
checkAuthentification() {
return new Promise((resolve, reject) => {
this.usersService.me()
.subscribe(res => {
resolve(res);
}, err => {
reject(err);
});
});
}
/**
* Login function
*
* @param {any} credentials
* @returns Promise
*
* @memberOf Auth
*/
login(credentials) {
this.http.apiUrl = credentials.server;
delete credentials.server;
return new Promise((resolve, reject) => {
this.http.post('/auth/local', credentials)
.map(res => res.json())
.subscribe(res => {
this.http.token = res.token;
this.storage.set('token', res.token);
resolve(res);
}, err => {
if (err.status === 401) {
reject(JSON.parse(err._body));
}
else {
reject(err);
}
});
});
}
/**
* Logout function
*
* @memberOf Auth
*/
logout() {
this.http.token = "";
this.storage.remove('token');
}
}
|
80ea4ba745e89b4ce1afeba1fe6f055972b2f380
|
[
"TypeScript"
] | 11
|
TypeScript
|
sylcastaing/Olaf-mobile
|
857685b7e8939f38531d881bf2f60d08143744f7
|
3a278ef4b76db1e335e4d606e2a7aab992f636b3
|
refs/heads/master
|
<repo_name>notoriouscoder4/RoomDatabaseRetrofit_1<file_sep>/app/src/main/java/com/jsm/roomdatabaseretrofit/Network/Api.java
package com.jsm.roomdatabaseretrofit.Network;
import com.jsm.roomdatabaseretrofit.Modal.Actor;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface Api {
@GET("data.php")
Call<List<Actor>> getAllActors();
}
|
4180a948b3e4d20b7be2891e18ecc2724419cf70
|
[
"Java"
] | 1
|
Java
|
notoriouscoder4/RoomDatabaseRetrofit_1
|
815e2840233f2b473c24a82584ff14863e190369
|
56098305de152aa52f2a96d49b4cb831e5d2e352
|
refs/heads/master
|
<repo_name>BlackMoon-Angle/shopping<file_sep>/src/js/login.js
window.onload = function () {
$('.account').click(function () {
$(this).addClass('active')
$(this).siblings('.borderleft').removeClass('active')
$(this)
.parent()
.siblings('.login_new_tabbody')
.children('.login')
.addClass('active2')
$(this)
.parent()
.siblings('.login_new_tabbody')
.children('.login2')
.removeClass('active2')
})
$('.borderleft').click(function () {
$(this).addClass('active')
$(this).siblings('.account').removeClass('active')
$(this)
.parent()
.siblings('.login_new_tabbody')
.children('.login2')
.addClass('active2')
$(this)
.parent()
.siblings('.login_new_tabbody')
.children('.login')
.removeClass('active2')
})
}<file_sep>/src/js/detail.js
window.onload = function () {
//导航菜单,二级菜单
twoList()
twoList_list()
function twoList() {
$('.hassub')
.on({
mouseenter: function () {
$(".head_section3_nav_div").eq($(this).index() - 1).css("display", "block")
},
mouseleave: function () {
$('.head_section3_nav_div').css("display", "none")
}
})
}
function twoList_list() {
$('.head_section3_nav_div')
.on({
mouseover: function () { $(this).css("display", "block") },
mouseout: function () { $(this).css("display", "none") }
})
}
//商品视图切换
ImgLook()
function ImgLook() {
$('.Img_tbody_tr > td > a').mouseenter(function () {
$('.Img_tbody_tr > td > a').children('span').css('display', 'none');
$(this).children('span').css('display', 'block');
//切换主视图图片
$(this)
.parent()//获取 a 标签的父元素 td
.parent()//获取 td 标签的父元素 tr
.parent()//获取 tr 标签的父元素 tbody
.parent()//获取 tbody 标签的父元素 table
.parent()//获取 table 标签的父元素 div
.siblings('.pBigPic')//获取 div 的兄弟元素 p
.children('span')//获取 p 的子元素 span
.children('img')//获取 span 的子元素 img
.attr('src', $(this).attr('rel'));//修改img的src值
//切换放大镜投影图片
$(this)
.parent()
.parent()
.parent()
.parent()
.parent()
.siblings('.big_box')
.children('img')
.attr('src', $(this).attr('rel'));
})
}
//放大镜
fdj()
function fdj() {
$(".mask").mouseover(function () {
$(".float_layer").show()
$(".big_box").show()
})
$(".mask").mouseout(function () {
$(".float_layer").hide()
$(".big_box").hide()
})
$(".mask").mousemove(function (e) {
var l = e.pageX - $(".pBigPic").offset().left - ($(".float_layer").width() / 2)
var t = e.pageY - $(".pBigPic").offset().top - ($(".float_layer").height() / 2)
if (l < 0) {
l = 0
}
if (l > $(this).width() - $(".float_layer").width()) {
l = $(this).width() - $(".float_layer").width()
}
if (t < 0) {
t = 0
}
if (t > $(this).height() - $(".float_layer").height()) {
t = $(this).height() - $(".float_layer").height()
}
$(".float_layer").css({
"left": l,
"top": t
})
var pX = l / ($(".mask").width() - $(".float_layer").width())
var pY = t / ($(".mask").height() - $(".float_layer").height())
$(".big_box img").css({
"left": -pX * ($(".big_box img").width() - $(".big_box").width()),
"top": -pY * ($(".big_box img").height() - $(".big_box").height())
})
})
}
//接受列表页传来的数据,渲染
Data_rendering();
function Data_rendering() {
//拿到localStorage的数据
//解析
const info = JSON.parse(localStorage.getItem('goodsInfo'));
//判断数是否存在
if (!info) {
alert('数据不存在!');
//跳转回列表页
window.location.href = '../pages/list.html';
}
//渲染页面
rendering();
function rendering() {
// 头部文字
$('.headText1').text(info.headText1);
$('.headText2').text(info.headText2);
$('.headText3').text(info.headText3);
$('.headText4').text(info.headText4);
$('.headText5').text(info.headText5);
// 商品主视图,投影图
$('.MaxImg1').attr('src', info.mi[0].MaxImg);
//商品主视图底部列表图
if (info.mi.length <= 4) {
//屏蔽多余的td
$('.mi_IMG5').css('display', 'none');
$('.mi_IMG6').css('display', 'none');
$('.mi_IMG7').css('display', 'none');
$('.mi_IMG8').css('display', 'none');
$('.mi_IMG9').css('display', 'none');
$('.mi_IMG1').attr('rel', info.mi[0].MaxImg);
$('.mi_IMG1 > img').attr('src', info.mi[0].MaxImg);
$('.mi_IMG2').attr('rel', info.mi[1].MaxImg);
$('.mi_IMG2 > img').attr('src', info.mi[1].MaxImg);
$('.mi_IMG3').attr('rel', info.mi[2].MaxImg);
$('.mi_IMG3 > img').attr('src', info.mi[2].MaxImg);
$('.mi_IMG4').attr('rel', info.mi[3].MaxImg);
$('.mi_IMG4 > img').attr('src', info.mi[3].MaxImg);
}
if (info.mi.length > 4) {
$('.mi_IMG5').css('display', 'block');
$('.mi_IMG6').css('display', 'block');
$('.mi_IMG7').css('display', 'block');
$('.mi_IMG8').css('display', 'block');
$('.mi_IMG9').css('display', 'block');
$('.mi_IMG1').attr('rel', info.mi[0].MaxImg);
$('.mi_IMG1 > img').attr('src', info.mi[0].MaxImg);
$('.mi_IMG2').attr('rel', info.mi[1].MaxImg);
$('.mi_IMG2 > img').attr('src', info.mi[1].MaxImg);
$('.mi_IMG3').attr('rel', info.mi[2].MaxImg);
$('.mi_IMG3 > img').attr('src', info.mi[2].MaxImg);
$('.mi_IMG4').attr('rel', info.mi[3].MaxImg);
$('.mi_IMG4 > img').attr('src', info.mi[3].MaxImg);
$('.mi_IMG5').attr('rel', info.mi[4].MaxImg);
$('.mi_IMG5 > img').attr('src', info.mi[4].MaxImg);
$('.mi_IMG6').attr('rel', info.mi[5].MaxImg);
$('.mi_IMG6 > img').attr('src', info.mi[5].MaxImg);
$('.mi_IMG7').attr('rel', info.mi[6].MaxImg);
$('.mi_IMG7 > img').attr('src', info.mi[6].MaxImg);
$('.mi_IMG8').attr('rel', info.mi[7].MaxImg);
$('.mi_IMG8 > img').attr('src', info.mi[7].MaxImg);
$('.mi_IMG9').attr('rel', info.mi[8].MaxImg);
$('.mi_IMG9 > img').attr('src', info.mi[8].MaxImg);
}
}
// 商品名称
$('.Title1').text(info.Title1);
$('.sex').text(info.sex);
$('.Title2').text(info.Title2);
// 价格
$('.Bmoney').text(info.Bmoney);
$('.Smoney').text(info.Smoney);
$('.zk').text(info.zk);
// 商品选择
$('.a_color > img').attr('src', info.mi[0].MaxImg);
// 尺码
$('.size1').text(info.size1);
$('.size2').text(info.size2);
$('.size3').text(info.size3);
$('.size4').text(info.size4);
$('.size5').text(info.size5);
$('.size6').text(info.size6);
$('.size7').text(info.size7);
$('.size8').text(info.size8);
//详细页与购物车页交互
buy();
function buy() {
$('.prodCartBtn').click(function () {
//先拿到数据,如果不存在数据,就用一个空数组代替
const cartList = JSON.parse(localStorage.getItem('cartList')) || [];
//判断数据是否存在
let exits = cartList.some(item => {
return item.id == info.id
})
if (exits) {
let data = null;
for (let i = 0; i < cartList.length; i++) {
if (cartList[i].id == info.id) {
data = cartList[i];
break;
}
}
//商品存在,如果持续点击添加购物车,则改变number数据
data.number++;
data.Allmoney = data.number * data.Bmoney;//总价格
}
else {
//如果不存在,则为数据添加number,总价格等属性做记录
info.number = 1;
info.Allmoney = info.Bmoney;
info.isSelect = false//默认不选中
cartList.push(info);
}
localStorage.setItem('cartList',JSON.stringify(cartList));
})
}
}
}<file_sep>/src/php/login.php
<?php
// 解决中文乱码
header('content-type: text/html;charset=utf-8;');
//接收login.html中,input输入框所输入的参数
$n = $_POST['username'];
$pw = $_POST['password'];
//链接数据库
$link = mysqli_connect('localhost', 'root', 'root', 'login');
//查看是否链接成功
// print_r($link);
//执行匹配,查看输入框中的账号和密码是否与数据库中的数据相匹配
$select_n_pw = "SELECT * FROM `login2` WHERE `username`='$n' AND `password`='$pw'";
$n_pw = mysqli_query($link,$select_n_pw);
//解析匹配结果
$n_pw_result = mysqli_fetch_assoc($n_pw);
// var_dump($n_pw_result);
//判断匹配结果
if ($n_pw_result) {//如果结果为true
header('location: ../pages/index.html');
}
else {
echo '用户名或密码错误!';
}
//断开链接
mysqli_close($link);
?>
<file_sep>/src/js/index.js
window.onload = function () {
//公告二级菜单渲染
$.ajax({
url: '/headerInfo',
data: {},
cache: false,
dataType: 'json',
success: function (res) {
$('#head_nav_div_ajax').html(res.notice.notice_list);
}
})
//商标列表
$.ajax({
url: '../lib/index.json',
dataType: 'json',
success: function (res) {
let str = '';
res.forEach(item => {
str +=`
<a href="javascript:void(0);"><img src="${item.img}" alt="${item.alt}"></a>
`
})
$('.brandinin').html(str);
}
})
//第一商品列表渲染
$.ajax({
url: '/shopList',
data: { cid: '3' },
cache: false,
dataType: 'json',
success: function (res2) {
function shopTime() {
let str = '';
res2.res.forEach(item => {
var et = new Date(item.endtime);
var nt = new Date();
var ct = parseInt((et.getTime() - nt.getTime()) / 1000);//时间差
var day = parseInt(ct / (60 * 60 * 24));//天
var hour = parseInt(ct / (60 * 60) % 24);//时
var min = parseInt(ct / 60 % 60);//分
var s = parseInt(ct % 60);//秒
str += `
<li>
<a href="../pages/list.html" target="_blank">
<img src="${item.img}" alt="">
<span class="tit1">${item.title}</span>
<span class="tit2">${item.slogan}</span>
<span class="tit3">${item.discount}</span>
<span class="time" id="timetwo0">
<span class="day"><i>${day}</i>天</span>
<span class="hour"><i>${hour}</i>时</span>
<span class="minute"><i>${min}</i>分</span>
<span class="second"><i>${s}</i>秒</span>
</span>
</a>
</li>
`
})
$('#list2in_ul').html(str);
}
shopTime();
setInterval(shopTime, 1000);
}
})
//第二列商品渲染
$.ajax({
url: '/shopList2',
data: { cid: '4' },
cache: false,
dataType: 'json',
success: function (res3) {
function shopTime2() {
let str = '';
res3.res.forEach(item => {
var et = new Date(item.endtime);
var nt = new Date();
var ct = parseInt((et.getTime() - nt.getTime()) / 1000);//时间差
var day = parseInt(ct / (60 * 60 * 24));//天
var hour = parseInt(ct / (60 * 60) % 24);//时
var min = parseInt(ct / 60 % 60);//分
var s = parseInt(ct % 60);//秒
str += `
<li>
<a href="../pages/list.html" target="_blank">
<img src="${item.img}">
<p class="list3tit1">${item.title}
<span>${item.discount}</span>
</p>
<span class="time2" id="timethree0">
<span class="day">
<i>${day}</i>天
</span>
<span class="hour">
<i>${hour}</i>时
</span>
<span class="minute">
<i>${min}</i>分
</span>
<span class="second">
<i>${s}</i>秒
</span>
</span>
</a>
</li>
`
})
$('#list3in_ul').html(str);
}
shopTime2();
setInterval(shopTime2, 1000);
}
})
//导航菜单,二级菜单
twoList()
twoList_list()
function twoList() {
$('.hassub')
.on({
mouseenter: function () {
$(".head_section3_nav_div").eq($(this).index() - 1).css("display", "block")
},
mouseleave: function () {
$('.head_section3_nav_div').css("display", "none")
}
})
}
function twoList_list() {
$('.head_section3_nav_div')
.on({
mouseover: function () { $(this).css("display", "block") },
mouseout: function () { $(this).css("display", "none") }
})
}
}<file_sep>/src/js/list.js
window.onload = function () {
//导航菜单,二级菜单
twoList()
twoList_list()
function twoList() {
$('.hassub')
.on({
mouseenter: function () {
$(".head_section3_nav_div").eq($(this).index() - 1).css("display", "block")
},
mouseleave: function () {
$('.head_section3_nav_div').css("display", "none")
}
})
}
function twoList_list() {
$('.head_section3_nav_div')
.on({
mouseover: function () { $(this).css("display", "block") },
mouseout: function () { $(this).css("display", "none") }
})
}
//列表商品请求
shopList();
//定义一个数组,用于接收json文件中的数据
let list_res = [];
function shopList() {
$.ajax({
url: '../lib/list.json',
dataType: 'json',
success: function (res) {
//渲染分页器
$('.M-box3').pagination({
pageCount: Math.ceil(res.length / 8),//总页数
current: 1,//当前页
jump: true,
coping: true,
homePage: '首页',
endPage: '末页',
prevContent: '上页',
nextContent: '下页',
callback: function (api) {
let curr = api.getCurrent();//获取,当前是第几页
var list = res.slice((curr - 1) * 8, curr * 8)//切割数据,slice(start, end),不包括尾部
HtmlList(list);//使用分页器时,渲染
}
});
//将list.json数据,传递给list_res
list_res = res;
//优先降第一页的数据渲染
HtmlList(res.slice(0, 8));
}
})
}
//渲染
function HtmlList(list) {
let str = '';
list.forEach(item => {
str += `
<div data-id="${item.id}" class="zt_25_list" style="margin-bottom: 36px;margin-left: 24px;cursor:pointer;">
<a class="jh_a" title="" target="_blank">
<img src="${item.img}"
alt="" class="zt_25_img">
</a>
<span class="zt_25_logobg">
<span class="BLB">
<img
src="http://0.image.al.okbuycdn.com//nbn/l72_50_detect/static/14ff119a643db529a889fd00d59b8776.jpg">
</span>
</span>
<a class="zt_25_link zt_25_link_a" title=""
target="_blank">${item.title}</a>
<span class="zt_25_link">¥
<span class="zt_25_pr">${item.money}</span>
<i>
<span>${item.zt_25_link2}</span>
</i>
</span>
</div>
`
$('.shopList').html(str);
});
//列表页详细页数据交互
$('.shopList > div').click(function () {
const DataId = $(this).data('id');//获取点击的div身上的id属性
//请求详情页数据
$.ajax({
url:'../lib/detail.json',
dataType: 'json',
success: function (res){
let data = null;
for(let i = 0;i < res.length;i++){
if(res[i].id == DataId){//如果id相同
data = res[i];//接受数据
break;//匹配后打断循环
}
}
//将数据存储到localStorage
localStorage.setItem('goodsInfo',JSON.stringify(data));
//跳转页面到详情页
window.location.href = '../pages/detail.html';
}
})
})
}
}<file_sep>/src/js/payment.js
window.onload = function () {
//导航菜单,二级菜单
twoList()
twoList_list()
function twoList() {
$('.hassub')
.on({
mouseenter: function () {
$(".head_section3_nav_div").eq($(this).index() - 1).css("display", "block")
},
mouseleave: function () {
$('.head_section3_nav_div').css("display", "none")
}
})
}
function twoList_list() {
$('.head_section3_nav_div')
.on({
mouseover: function () { $(this).css("display", "block") },
mouseout: function () { $(this).css("display", "none") }
})
}
//购物车渲染
buy_pay();
function buy_pay() {
//获取数据
const cartList = JSON.parse(localStorage.getItem('cartList'));
//判断是否存在数据
if (!cartList) {
alert('购物车为空!')
}
else {
binHtml()
bindEvent()
}
function binHtml() {//整体渲染
let selectAll = cartList.every(item => {
return item.isSelect === true;
})
let str = '';
let str2 = '';
let str3 = '';
str3 = `<label><input type="checkbox" id="check-goods-all" ${selectAll ? 'checked' : ''} /><span id="checkAll">全选</span></label>`
$('.col_all').html(str3);
cartList.forEach(item => {
str += `
<div class="shop_box">
<label class="shop_all"><input data-id=${ item.id} type="checkbox" id="check-goods-alone" ${item.isSelect ? 'checked' : ''} /></label>
<div class="shop_img">
<img src="${item.mi[0].MaxImg}" alt="" width="100%" height="100%">
</div>
<div class="shop_name">
<p style="font-size: 15px;">${item.Title2}</p>
</div>
<div class="shop_money">
<p>¥<span class="money_span">${item.Bmoney}</span></p>
</div>
<div class="shop_num">
<input class="shop_num_add" type="button" value="+" data-id=${ item.id}>
<input class="shop_num_number" type="text" name="" id="" value="${item.number}" disabled="value">
<input class="shop_num_reduce" type="button" value="-" data-id=${ item.id}>
</div>
<div class="shop_money2">
<p>¥<span class="money_span2">${item.Allmoney}</span></p>
</div>
<div class="shop_delect">
<input class="shop_delect_d" type="button" value="删除" data-id=${ item.id}>
</div>
</div>
`
})
$('#shop_wrap').html(str);
let selectArr = cartList.filter(item => item.isSelect)
let selectNumber = 0;//选中商品数量计算
let selectPrice = 0;//总价格
selectArr.forEach(item => {
selectNumber += item.number
selectPrice += item.Allmoney * 1
})
str2 += `
<div class="shop_choose">
<p>商品数量:<span class="shop_choose_num">${selectNumber}</span></p>
</div>
<div class="shop_Allmoney">
<p>总价格:¥<span class="shop_Allmoney_num">${selectPrice}</span></p>
</div>
<div class="shop_empty">
<input class="delect_all" type="button" value="清空购物车">
</div>
<div class="shop_pay">
<input type="button" value="支付" ${ selectArr.length ? '' : 'disabled'}>
</div>
`
$('.main_box3').html(str2);
}
//按钮事件
function bindEvent() {
//全选按钮的事件
$('body').on('change', '#check-goods-all', function () {
//当全选按钮被选上时
//其他的选择按钮也被选中
cartList.forEach(item => {
item.isSelect = this.checked;
})
//重新渲染页面
binHtml();
//重新储存数据,防止页面刷新的时候,重置按钮
localStorage.setItem('cartList', JSON.stringify(cartList));
})
//单选按钮的事件
$('body').on('change', '#check-goods-alone', function () {
//获取自己身上的id
const id = $(this).data('id');
//从数据中,匹配到id相同的数据,修改isSelect的值
cartList.forEach(item => {
if (item.id == id) {
item.isSelect = !item.isSelect
}
})
// //重新渲染页面
binHtml();
// //重新储存数据,防止页面刷新的时候,重置按钮
localStorage.setItem('cartList', JSON.stringify(cartList));
})
//减少按钮
$('body').on('click', '.shop_num_reduce', function () {
//获取自己身上的id
const id = $(this).data('id');
//从数据中,匹配到id相同的数据,修改number和Allmoney的值
cartList.forEach(item => {
if (item.id == id) {
//当number为1的时候,就停止继续减少
item.number > 1 ? item.number-- : '';
item.Allmoney = item.Bmoney * item.number;
}
})
// //重新渲染页面
binHtml();
// //重新储存数据,防止页面刷新的时候,重置按钮
localStorage.setItem('cartList', JSON.stringify(cartList));
})
//增加按钮
$('body').on('click', '.shop_num_add', function () {
//获取自己身上的id
const id = $(this).data('id');
//从数据中,匹配到id相同的数据,修改number和Allmoney的值
cartList.forEach(item => {
if (item.id == id) {
item.number++;
item.Allmoney = item.Bmoney * item.number;
}
})
// //重新渲染页面
binHtml();
// //重新储存数据,防止页面刷新的时候,重置按钮
localStorage.setItem('cartList', JSON.stringify(cartList));
})
//删除按钮
$('body').on('click', '.shop_delect_d', function () {
//获取自己身上的id
const id = $(this).data('id');
//从数据中,匹配到id相同的数据,进行删除
cartList.forEach(item => {
if (item.id == id) {
cartList.splice(item.index,1)
}
})
//重新渲染页面
binHtml();
//重新储存数据,防止页面刷新的时候,重置按钮
localStorage.setItem('cartList', JSON.stringify(cartList));
})
//清空按钮
$('body').on('click', '.delect_all', function () {
console.log('1')
var ls_list = JSON.parse(localStorage.getItem('cartList'));//获取数组
ls_list.splice(0);
// //重新渲染页面
binHtml();
// //重新储存数据,防止页面刷新的时候,重置按钮
localStorage.setItem('cartList', JSON.stringify(ls_list));
buy_pay();
})
}
}
}<file_sep>/src/php/register.php
<?php
// 解决中文乱码
header('content-type: text/html;charset=utf-8;');
//接收register.html中,input输入框所输入的参数
$n = $_POST['username'];
$pw = $_POST['<PASSWORD>'];
$cc = $_POST['codecheck'];
$cc2 = $_POST['codecheck2'];
//链接数据库
$link = mysqli_connect('localhost', 'root', 'root', 'login');
//查看是否链接成功
// print_r($link);
//判断
if ($cc = $cc2) { //如果结果为true
//添加数据到数据库
$new_user = mysqli_query($link, "INSERT INTO `login2` VALUES(null, '$n', '$pw')");
if ($new_user) {
echo "<script>alert('操作成功');parent.location.href='../pages/login.html';</script>";
}
} else {
echo "<script>alert('验证码不正确,请重新输入!');parent.location.href='../pages/register.html';</script>";
}
|
4ef3d2cec80a85494f792141433a815622501d96
|
[
"JavaScript",
"PHP"
] | 7
|
JavaScript
|
BlackMoon-Angle/shopping
|
f6782772aec1e07e917dc65a397db8ce118e491a
|
cbdc0c0e231a5576ec7dbe1d089e4546063c78e2
|
refs/heads/master
|
<repo_name>madhusweb/devops-practice<file_sep>/madhu-script.sh
#!/bin/bash
echo "Hello world v2"
|
fbb3822b44d4f7589322ac6d5bd7d2180f623db8
|
[
"Shell"
] | 1
|
Shell
|
madhusweb/devops-practice
|
4fab91a6a3be0f088e34dd7a8935984f4e46c35f
|
3ba85cd1a26ff416cf811612d4ddc5a2130cb442
|
refs/heads/master
|
<file_sep># LeafCrap
A scrapper for extracting the strains info and their images from Leafly.
## Legal note
This script is only for personal usage and not for any profitable purpose. We're not responsible for what people use for and leafly's data in under copyright by their brand. Leafly would probably take action against any profitiable usage.
Also if Leafly wants us to take down this repository, they can just create an issue and we will remove the code as soon as possible.<file_sep>const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.leafly.com/strains');
let texts = await page.evaluate(() => {
let data = [];
let elements = document.getElementsByClassName('mx-lg md:mx-xxl');
for (var element of elements)
data.push(element.textContent);
return data;
});
console.log(texts);
await browser.close();
})();
|
148a8ef6ec0b41ac3a1fedbed68b807c3d8e8f62
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
leafcrap/leafcrap
|
1f043f75092f6e0408a5f00a9e82a8c93cd96474
|
e1c78cf588f86a298ce20dd3b575f6f8e0a023bb
|
refs/heads/main
|
<file_sep># The-Pomodoro-Technique<file_sep>#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <conio.h>
int sec=0,min=25,auxmin=25;
int minb=4,auxb=4,minlb=30,auxlb=30;
int pom=0,psr=0;
UINT_PTR timer,timRes;
void CALLBACK Reset(HWND hwnd, UINT uMsg, UINT timerId, DWORD dwTime){
if(kbhit()){
psr=getch();
if(psr=='5'){
psr=0;
printf("Press any key to continue:\n\n");
getch();
}
if(psr=='6'){
KillTimer(NULL, timer);
psr=0;
}
if(psr=='7'){
sec=0,min=auxmin,minb=auxb,minlb=auxlb,pom=0,psr=0;
}
}
}
void CALLBACK Timer(HWND hwnd, UINT uMsg, UINT timerId, DWORD dwTime)
{
//Work Session
if(min>=0 && pom!=4){
system("cls");
printf("Work Session:\n\n");
printf("%dm:%ds\n\n",min,sec);
printf("Pause/Play:5\nStop:6\nReset:7\n\n");
sec--;
if(sec<0){
sec=59;
min--;}
if(min==0 && sec==0){
pom++;
Beep(0, 1000);
Beep(800, 100);
Beep(600, 100);
Beep(400, 100);
}}
//Break Session
if(min<0 && pom!=4){
system("cls");
printf("Break Session:\n\n");
printf("%dm:%ds\n\n",minb,sec);
printf("Pause/Play:5\nStop:6\nReset:7\n\n");
sec--;
if(sec<0){
sec=59;
minb--;}
if(minb==0 && sec==0){
Beep(0, 1000);
Beep(400, 100);
Beep(600, 100);
Beep(800, 100);
min=auxmin;
minb=auxb;
}}
//Long Break Session
if(pom==4){
system("cls");
printf("Long Break Session:\n\n");
printf("%dm:%ds\n\n",minlb,sec);
printf("Pause/Play:5\nStop:6\nReset:7\n\n");
sec--;
if(sec<0){
sec=59;
minlb--;}
if(minlb==0 && sec==0){
Beep(0, 1000);
Beep(400, 100);
Beep(600, 100);
Beep(800, 100);
min=auxmin;
minb=auxb;
pom=0;
}}
}
int main(){
int change;
int ready=0;
MSG msg;
SetConsoleTitle("The Pomodoro Technique");
do{
printf("Change time:\n\n");
printf("Work Session: Press 1\n");
printf("Break Session: Press 2\n");
printf("Long Break Session: Press 3\n");
printf("Use default: Press 0\n\n");
scanf("%d",&change);
//Change Work Session Time
if(change==1){
printf("\nEnter the desired time:\n\n");
scanf("%d",&min);
auxmin=min;
}
//Change Break Session Time
if(change==2){
printf("\nEnter the desired time:\n\n");
scanf("%d",&minb);
minb--;
auxb=minb;
}
//Change Long Break Session Time
if(change==3){
int lb;
printf("\nChoose the desired time:\n1:30 minutes\n2:10 minutes\n\n");
scanf("%d",&lb);
if(lb==1)
minlb=30,auxlb=30;
else if(lb==2)
minlb=10,auxlb=10;
}
//Default
if(change==0)
min=25,auxmin=25,minb=4,auxb=4,minlb=30,auxlb=30;
printf("\nPress 4 if all settings are made or 1 to continue configuring\n\n");
scanf("%d",&ready);
system("cls");
}while(ready!=4);
timer = SetTimer(NULL, 0, 1000,(TIMERPROC) &Timer);
timRes = SetTimer(NULL, 0, 10,(TIMERPROC) &Reset);
while(GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);}
return 0;
}
|
0a2f047f490886b882c125ae61643ba8ab2916e8
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
GabrielSilvaL/The-Pomodoro-Technique
|
811de9f112e1aaae411f65dede8032142c9d016b
|
60ce5d325f3e457e8d66d151858de545f62c33c0
|
refs/heads/soul3
|
<repo_name>experimental-platform/continuous-delivery<file_sep>/build.sh
#!/usr/bin/env bash
set -e
DEBUG=/bin/false
${DEBUG} && set -x
${DEBUG} && echo "\n\nALL VARIABLES:\n"
${DEBUG} && set
${DEBUG} && echo "ALL VARIABLES DONE\n\n"
# TODO: does build but not use the built "ubuntu" :(
CHANNEL=${TRAVIS_BRANCH}
function push_image() {
local i=0
local image=$1
while true; do
docker push ${image} > /dev/stderr | true
if [[ ${PIPESTATUS[0]} -eq 0 ]]; then
break
fi
if [[ ${i} -gt 10 ]]; then
echo -e "\n\n\nERROR: Couldn't push ${image}\n"
exit 23
fi
i=$[$i+1]
echo -e "Sleeping 15 seconds."
sleep 15;
done
}
function build_image() {
local j=0
local docker_tag=$1
local docker_dir=$2
while true; do
echo -e "\nBuilding Image ${docker_tag}, round ${j}"
docker build -t ${docker_tag} ${docker_dir} > /dev/stderr | true
if [[ ${PIPESTATUS[0]} -eq 0 ]]; then
break
fi
if [[ ${j} -gt 10 ]]; then
echo -e "\n\n\nERROR: Couldn't build ${docker_tag}\n"
exit 23
fi
j=$[$j+1]
echo -e "Sleeping 15 seconds."
sleep 15;
done
}
build_repo() {
repo="$1"
if [[ -f ./${repo}/Dockerfile ]]; then
NAME=${repo#platform-}
cd ${repo}
echo -e "\n\n\nBUILDING ${NAME}:${VERSION}\n"
if [ -x ./ci-build.sh ]; then
./ci-build.sh
elif [ -n "$(find . -maxdepth 1 -name '*\.go')" ]; then
curl -L https://raw.githubusercontent.com/experimental-platform/build-scripts/master/go-build.sh | TRAVIS_REPO_SLUG="experimental-platform/$repo" bash
fi
build_image experimentalplatform/${NAME}:${VERSION} .
push_image experimentalplatform/${NAME}:${VERSION}
echo -e "\n\n\nDEPLOYING ${NAME}:${VERSION}\n"
cd ..
else
echo " * Skipping $repo -- no Dockerfile"
fi
}
if [[ -z ${CHANNEL+x} ]]; then
echo "CHANNEL not set, exiting."
exit 23
elif [[ -z "$DEPLOY" ]]; then
echo "PREPARING ${CHANNEL} FOR TEST"
export VERSION=${CHANNEL}-testing
for repo in platform-*; do
build_repo "$repo"
done
echo -e "\n\nCHANNEL ${VERSION} BUILT!\n"
else
echo "DEPLOYING ${CHANNEL}"
export VERSION=${CHANNEL}
for repo in platform-*; do
if [[ -f ./${repo}/Dockerfile ]]; then
NAME=${repo#platform-}
if [[ "$NAME" == "configure" ]]; then
echo "Not retagging configure"
else
echo -e "\n\n\nRETAGGING $NAME:${VERSION}\n"
docker tag -f experimentalplatform/${NAME}:${VERSION}-testing experimentalplatform/${NAME}:${VERSION}
push_image experimentalplatform/${NAME}:${VERSION}
fi
fi
done
# TODO: in five years when we're all fat, rich and have lots of time: refactor this into a function
cd platform-configure
[ -x ./ci-build.sh ] && ./ci-build.sh || true
echo -e "\n\nBUILDING experimentalplatform/configure:${VERSION}\n"
build_image experimentalplatform/configure:${VERSION} .
echo "Assertion: None of the systemd units may have the word 'testing' in it."
[[ $(docker run -ti --rm experimentalplatform/configure:${VERSION} bash -c 'grep -l testing /services/*-protonet.service | wc -l') =~ 0 ]]
echo -e "\n\nDEPLOYING experimentalplatform/configure:${VERSION}\n"
push_image experimentalplatform/configure:${VERSION}
echo -e "\n\nCHANNEL ${VERSION} RELEASED!\n"
fi
<file_sep>/release-helper.sh
#!/usr/bin/env bash
set -e
CHANNEL=${1:-alpha}
function main() {
available_channels="development alpha soul3"
if [[ ! ${available_channels} =~ ${CHANNEL} ]]; then
echo "INVALID channel '${CHANNEL}'"
exit 23
fi
if [[ "${CHANNEL}" == "development" ]]; then
CHANNEL="alpha"
PRODUCT_CHANNEL="development"
else
PRODUCT_CHANNEL="master"
fi
echo "Working on out release channel ${CHANNEL} and product channel ${PRODUCT_CHANNEL}"
echo -e "\n\n\nEXPERIMENTAL-PLATFORM: ${CHANNEL}\n\n"
git checkout ${CHANNEL}
git pull
git submodule update --init
git submodule foreach git fetch --all
echo -e "\n\n\nEVERYTHING ELSE: ${PRODUCT_CHANNEL}\n\n"
git submodule foreach git checkout ${PRODUCT_CHANNEL}
cd platform-ubuntu; git checkout latest; cd ..
cd platform-buildstep; git checkout herokuish; cd ..
git submodule foreach git pull
echo "ALL REPOSITORIES UPDATED. PLEASE REVIEW, COMMIT AND PUSH NOW."
}
main
|
003448fbd023b5c920750120b0246ad3b628ceaa
|
[
"Shell"
] | 2
|
Shell
|
experimental-platform/continuous-delivery
|
6dc60e0a7855fbc1a7ef7c7801c3e18ca299cbed
|
cf73b8689cd5b7a6074912a7e4828eb120a82580
|
refs/heads/master
|
<repo_name>ariqnfl/mountnesia<file_sep>/app/Http/Controllers/MountController.php
<?php
namespace App\Http\Controllers;
use App\Location;
use App\Mount;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class MountController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$mounts = Mount::paginate(6);
return view('mount.index', compact('mounts'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('mount.create');
}
public function nampilinGambar()
{
$locations = Location::all();
$mounts = Mount::all();
return view('index', compact('locations', 'mounts'));
}
public function showGambar($id)
{
$mounts = Mount::findOrFail($id);
return view('item', compact('mounts'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$datas = $request->all();
if ($request->file('imageCover')) {
$file = Storage::disk('public')->put('cover', $request->imageCover);
$datas['imageCover'] = $file;
}
if ($request->file('image_1')) {
$file = Storage::disk('public')->put('image1', $request->image_1);
$datas['image_1'] = $file;
}
if ($request->file('image_2')) {
$file = Storage::disk('public')->put('image2', $request->image_2);
$datas['image_2'] = $file;
}
if ($request->file('image_3')) {
$file = Storage::disk('public')->put('image3', $request->image_3);
$datas['image_3'] = $file;
}
Mount::create($datas);
return redirect(route('location.create'))->with('status', 'mantap');
}
/**
* Display the specified resource.
*
* @param \App\Mount $mount
* @return \Illuminate\Http\Response
*/
public function show(Mount $mount)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Mount $mount
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$mount = Mount::findOrFail($id);
return view('mount.edit', compact('mount'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Mount $mount
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$mount = Mount::findOrFail($id);
$data = $request->all();
if ($request->hasFile('imageCover')) {
$file = $request->file('imageCover')->store('cover', 'public');
$data['imageCover'] = $file;
Storage::delete('public' . $mount->imageCover);
}
if ($request->hasFile('image_1')) {
$file = $request->file('image_1')->store('image1', 'public');
$data['image_1'] = $file;
Storage::delete('public' . $mount->image_1);
}
if ($request->hasFile('image_2')) {
$file = $request->file('image_2')->store('image2', 'public');
$data['image_2'] = $file;
Storage::delete('public' . $mount->image_2);
}
if ($request->hasFile('image_3')) {
$file = $request->file('image_3')->store('image3', 'public');
$data['image_3'] = $file;
Storage::delete('public' . $mount->image_3);
}
$mount->update($data);
return redirect(route('mounts.edit', ['id' => $mount->id]))->with('status', 'mantul update');
}
/**
* Remove the specified resource from storage.
*
* @param \App\Mount $mount
* @return \Illuminate\Http\Response
*/
public function destroy(Mount $mount)
{
//
}
public function shopNow($id)
{
$mount = Mount::findOrFail($id);
return view('order',compact('mount'));
}
}
<file_sep>/README.md
# Mountnesia
build with laravel 5.7.13
<file_sep>/app/Mount.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mount extends Model
{
public function locations()
{
return $this->belongsTo('App\Location','location_id','id');
}
protected $fillable = [
'name', 'height', 'terms', 'desc', 'location_id', 'price', 'imageCover', 'image_1', 'image_2','image_3','link','waktu'
];
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
Route::get('/admin', 'HomeController@index')->name('home');
Route::get('/','MountController@nampilinGambar')->name('depan');
Route::get('/mountain/{id}','MountController@showGambar')->name('gambar');
Route::get('/mountain/tickets/{id}','MountController@shopNow')->name('shop');
Route::get('/ajax/location/search','LocationController@ajaxSearch')->name('ajax.search');
Route::resource('location','LocationController');
Route::resource('mounts','MountController');
Route::resource('order','OrderController');
Route::resource('user','UserController');
<file_sep>/app/Location.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Location extends Model
{
public function mounts()
{
return $this->hasOne('App\Mount','location_id','id');
}
//
protected $fillable = [
'name'
];
}
<file_sep>/app/Http/Controllers/LocationController.php
<?php
namespace App\Http\Controllers;
use App\Location;
use Illuminate\Http\Request;
class LocationController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$locations = Location::paginate(8);
return view('location.index',compact('locations'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('location.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$datas = $request->all();
Location::create($datas);
return redirect(route('location.create'))->with('status','created');
}
/**
* Display the specified resource.
*
* @param \App\Location $location
* @return \Illuminate\Http\Response
*/
public function show(Location $location)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Location $location
* @return \Illuminate\Http\Response
*/
public function edit(Location $location)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Location $location
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Location $location)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Location $location
* @return \Illuminate\Http\Response
*/
public function destroy(Location $location)
{
$location->delete();
return redirect(route('location.index'));
}
public function ajaxSearch(Request $request)
{
$keyword = $request->get('q');
$location = Location::where('name','LIKE',"%$keyword%")->get();
return $location;
}
}
<file_sep>/database/migrations/2018_11_24_191535_create_mounts_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMountsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('mounts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('height');
$table->text('terms');
$table->text('desc');
$table->unsignedInteger('location_id');
$table->integer('price');
$table->string('imageCover')->nullable();
$table->string('image_1')->nullable();
$table->string('image_2')->nullable();
$table->timestamps();
$table->foreign('location_id')->references('id')->on('locations');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('mounts');
}
}
|
81732d823768be75a47bf3241ace73483c610cd6
|
[
"Markdown",
"PHP"
] | 7
|
PHP
|
ariqnfl/mountnesia
|
4ff1b59cbcd443f2d1261fbb05967f1ceefae917
|
6712bae720906d07b59305bcbf023dc69f159d62
|
refs/heads/master
|
<file_sep><?php
echo "<h1>WELCOME TO THE DASHBOARD</h1>";
?><file_sep><?php
$uname="";
$err_uname="";
$pass="";
$err_pass="";
$err_msg="";
$hasError=false;
$flag=false;
$username="root";
$servername="localhost";
$password="";
$db_name="mydb";
if(isset($_POST["login"])){
if(empty($_POST["uname"])){
$err_uname="Username Required";
$hasError =true;
}
else{
$uname = htmlspecialchars($_POST["uname"]);
}
if(empty ($_POST["pass"])){
$err_pass="Password Required";
$hasError = true;
}
else{
$pass=htmlspecialchars($_POST["pass"]);
}
if(!$hasError){
$conn = mysqli_connect($servername,$username,$password,$db_name);
if(!$conn){
die("Connection failed: " .mysqli_connect_error());
}
$query="SELECT * FROM user";
$results=mysqli_query($conn,$query);
$flag=false;
if($query = mysqli_query($conn, "SELECT username,password FROM user WHERE username='$uname' AND password='$<PASSWORD>'")){
$flag=true;
}
if(!$flag){
$err_uname="Invalid Credentials!";
}
else{
//echo "<th> log in suceess</td>";
if(mysqli_num_rows($results)>0){
echo '<table border="1" style="border-collapse:collapse;">';
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Username</th>";
echo "<th>Usertype</th>";
while($row=mysqli_fetch_assoc($results)){
echo "<tr>";
echo "<td>".$row["id"]."</td>";
echo "<td>".$row["username"]."</td>";
echo "<td>".$row["usertype"]."</td>";
echo '</tr>';
}
echo '</table>';
}
}
}
}
?><file_sep><?php
if (!isset($_COOKIE["username"])) {
header("Location: login.php");
}
?>
<style>
table, tr, td {
border: 1px solid black;
padding: 5px;
}
</style>
<html>
<title>Dashboard</title>
<body>
<?php
$books = simplexml_load_file("books.xml");
if (count($books->name) == 0) {
echo "<h1>No books to show</h1>";
}
else { ?>
<table style="">
<tr>
<td>
<a href="addBook.php"> Add a new book </a>
</td>
</tr>
<tr style="text-transform: uppercase; text-decoration: underline; color: green;">
<td> sr no. </td>
<td> name </td>
<td> publisher </td>
<td> isbn </td>
<td> price </td>
<td> image </td>
<td> delete </td>
</tr>
</table>
<?php }
?>
</body>
</html><file_sep><?php include_once "php_code/registration_validation.php" ;?>
<html>
<head>
<title>KENAKATA SUPERSHOP</title>
</head>
<body>
<center>
<h1>Welcome to Registration</h1>
</center>
<center>
<form action="" method="POST">
<table>
<tr>
<td align="left" style="font-size: 30px;"><span style="color:white;">User Name:</span></td>
<td align="left"><input type="text" placeholder="User name..." value="<?php echo $uname;?>" name="uname"></td>
<td align="left"><span style="color:white;">*<?php echo $err_uname;?></span></td>
</tr>
<tr>
<td align="left"style="font-size: 30px;"><span style="color:white;">Password:</span></td>
<td align="left"><input type="password" placeholder="Password..." value="<?php echo $pass;?>" name="pass"></td>
<td align="left"><span style="color:white;">*<?php echo $err_pass;?></span></td>
</tr>
<tr>
<td colspan="3" align="right">
<input type="submit" name="ok" value="REGISTER">
</td>
</tr>
</table>
</form>
</center>
</header>
</body>
</html><file_sep><?php
$name="";
$err_name="";
$uname="";
$err_uname="";
$pass="";
$err_pass="";
$cpass="";
$err_cpass="";
$email="";
$err_email="";
$phoneCode="";
$err_phoneCode="";
$phoneNum="";
$err_phoneNum="";
$address="";
$err_address="";
$city="";
$err_city="";
$state="";
$err_state="";
$postalCode="";
$err_postalCode="";
$dobDay="";
$dobMonth="";
$dobYear="";
$err_dob="";
$gender="";
$err_gender="";
$refer="";
$err_refer="";
$bio="";
$err_bio="";
$has_err=false;
if(isset($_POST["register"])){
//name validate
if(empty($_POST["name"])){
$err_name="Please Enter Name!";
$has_err=true;
}
elseif(strpos($_POST["name"],"abcdefg")){
$err_name="Name Can Not Have Sequence Like 'abcdefg'";
$has_err=true;
}
else{
$name=htmlspecialchars($_POST["name"]);
}
//username validate
if(empty($_POST["uname"])){
$err_uname="Please Enter Username!";
$has_err=true;
}
elseif((strlen($_POST["uname"])<6)){
$err_uname="Username Must Contain 6 characters!";
$has_err=true;
}
elseif(strpos($_POST["uname"]," ")){
$err_uname="Username Can Not Contain Any Space!";
$has_err=true;
}
else{
$uname=htmlspecialchars($_POST["uname"]);
}
//password validate
if(empty($_POST["pass"])){
$err_pass="Please Enter Password!";
$has_err=true;
}
elseif(strlen($_POST["pass"])<8){
$err_pass="Password Must Be 6 characters Long!";
$has_err=true;
}
elseif(!strpos($_POST["pass"],"#") || !strpos($_POST["pass"],"?")){
$err_pass="Password Must Contain '#' or '?'.";
$has_err=true;
}
elseif(!strpos($_POST["pass"],"1")){
$err_pass="Password Must Contain 1 Numeric!";
$has_err=true;
}
elseif(strtolower($_POST["pass"])==$_POST["pass"] || strtolower($_POST["pass"])==$_POST["pass"]){
$err_pass="Password must contain 1 Upper and Lowercase letter.";
$has_err=true;
}
else{
$pass=htmlspecialchars($_POST["pass"]);
}
//confirm password validate
if(empty($_POST["cpass"])){
$err_cpass="Please Enter Confirm Password!";
$has_err=true;
}
elseif(!strcmp($_POST["cpass"],strtoupper($_POST["pass"]))){
$err_cpass="Password and Confirm Password must be same!";
$has_err=true;
}
else{
$cpass=htmlspecialchars($_POST["cpass"]);
}
//phonecode validate
if(empty($_POST["phoneCode"])){
$err_phoneCode="Please Enter Phone Code";
$has_err=true;
}
elseif(strlen($_POST["phoneCode"]) != 3){
$err_phoneCode="Phone Code Must Contain 3 Characters!";
$has_err=true;
}
elseif(!is_numeric($_POST["phoneCode"])){
$err_phoneCode="Phone Code Must Be Numeric!";
$has_err=true;
}
else{
$phoneCode=htmlspecialchars($_POST["phoneCode"]);
}
//phone number validate
if(empty($_POST["phoneNum"])){
$err_phoneNum="Please Enter Phone Number!";
$has_err=true;
}
elseif(strlen($_POST["phoneNum"]) != 10){
$err_phoneNum="Phone Number Must Contain 10 characters!";
$has_err=true;
}
elseif(!is_numeric($_POST["phoneNum"])){
$err_phoneNum="Phone Number Must Be Numeric!";
$has_err=true;
}
else{
$phoneNum=htmlspecialchars($_POST["phoneNum"]);
}
//address validate
if(empty($_POST["address"])){
$err_address="Address Can Not Be Empty!";
$has_err=true;
}
else{
$address=htmlspecialchars($_POST["address"]);
}
//city validate
if(empty($_POST["city"])){
$err_city="City Can Not Be Empty!";
$has_err=true;
}
else{
$city=htmlspecialchars($_POST["city"]);
}
//state validate
if(empty($_POST["state"])){
$err_state="State Can Not Be Empty!";
$has_err=true;
}
else{
$state=htmlspecialchars($_POST["state"]);
}
//postcode validate
if(empty($_POST["postalCode"])){
$err_postalCode="Postal Code Can Not Be Empty!";
$has_err=true;
}
else{
$postalCode=htmlspecialchars($_POST["postalCode"]);
}
//gender validate
if(!isset($_POST["gender"])){
$err_gender="Gender Required!";
$has_err=true;
}
else{
$gender=htmlspecialchars($_POST["gender"]);
}
//bio validate
if(empty($_POST["bio"])){
$err_bio="Bio Can Not Be Empty!";
$has_err=true;
}
else{
$bio=htmlspecialchars($_POST["bio"]);
}
//details
if(!$has_err){
$details=array("Name: ".$name,"Username: ".$uname,"Password: ".$<PASSWORD>,"Email: ".$email,"Phone: +".$phoneCode.$phoneNum,"Address: ".$address,"City: ".$city,"State: ".$state,"Postal Code: ".$postalCode,"Birth Date: ".$dobDay.", ".$dobMonth.", ".$dobYear,"Gender: ".$gender,"Referred: ".implode(',', $_POST['refer']),"Bio: ".$bio);
foreach($details as $detail){
echo "<h4>".$detail."</h4><br>";
}
}
}
?>
<html>
<head>
<title>Club Registration</title>
</head>
<body>
<center>
<table>
<tr>
<td>
<form action="" method="POST">
<fieldset>
<legend><h1>Club Member Registration</h1></legend>
<table>
<tr>
<td align="right">Name:</td>
<td><input type="text" name="name"> <?php echo $err_name ?></td>
</tr>
<tr>
<td align="right">Username:</td>
<td><input type="text" name="uname"> <?php echo $err_uname ?></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><input type="password" name="pass"> <?php echo $err_pass ?></td>
</tr>
<tr>
<td align="right">Confirm Password:</td>
<td><input type="password" name="cpass"> <?php echo $err_cpass ?></td>
</tr>
<tr>
<td align="right">Email:</td>
<td><input type="text" name="email"> <?php echo $err_email ?></td>
</tr>
<tr>
<td align="right">Phone:</td>
<td>
<input type="text" placeholder="Code" size="3" name="phoneCode"> <?php echo $err_phoneCode ?>-
<input type="text" placeholder="Number" size="9" name="phoneNum"> <?php echo $err_phoneNum ?>
</td>
</tr>
<tr>
<td align="right">Address:</td>
<td><input type="text" placeholder="Street name" name="address"> <?php echo $err_address ?></td>
</tr>
<tr>
<td></td>
<td>
<input type="text" placeholder="City" size="6" name="city"> <?php echo $err_city ?>-
<input type="text" placeholder="State" size="6" name="state"> <?php echo $err_state ?>
</td>
</tr>
<tr>
<td></td>
<td><input type="text" placeholder="Postal Code" name="postalCode"> <?php echo $err_postalCode ?></td>
</tr>
<tr>
<td align="right">Birth Date:</td>
<td>
<select name="dobDay">
<?php
echo "<option disabled selected>Day</option>";
for($i=1; $i<32; $i++){
echo "<option>".$i."</option>";
}
?>
</select>
<select name="dobMonth">
<?php
$months=array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
echo "<option disabled selected>Month</option>";
for($i=0; $i<12; $i++){
echo "<option>".$months[$i]."</option>";
}
?>
</select>
<select name="dobYear">
<?php
echo "<option disabled selected>Year</option>";
for($i=1990; $i<2021; $i++){
echo "<option>".$i."</option>";
}
?>
</select>
<?php echo $err_dob ?>
</td>
</tr>
<tr>
<td align="right">Gender:</td>
<td>
<input type="radio" name="gender"> Male
<input type="radio" name="gender"> Female <?php echo " |".$err_gender ?>
</td>
</tr>
<tr>
<td>Where did you hear about us?</td>
<td>
<input type="checkbox" name="refer[]" value="A Friend or Colleague"> Movies<br>
<input type="checkbox" name="refer[]" value="Google"> Music <br>
<input type="checkbox" name="refer[]" value="Blog Post"> Programming<br>
<input type="checkbox" name="refer[]" value="News Article"> Travelling <?php echo "<br>".$err_refer ?>
</td>
</tr>
<tr>
<td align="right">Bio:</td>
<td><textarea name="bio"></textarea> <?php echo $err_bio ?></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="register" value="Register">
</td>
</tr>
</table>
</fieldset>
</form>
</td>
</tr>
</table>
</center>
</body>
</html><file_sep><?php include "validate_login.php" ?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="" method="post" style="width: 300px";>
<fieldset style="background-color: lightgray;">
<table align="center">
<h1 align="center">Login</h1>
<tr style="line-height: 50px;">
<td>
Username:
</td>
</tr>
<tr style="line-height: 50px;">
<td>
<input type="text" name="uname">
</td>
</tr>
<tr style="line-height: 50px;">
<td>
Password:
</td>
</tr>
<tr style="line-height: 50px;">
<td>
<input type="<PASSWORD>" name="<PASSWORD>">
<input type="submit" name="login" value="Login" style="background-color: green; color: white";>
</td>
</tr>
<tr>
<td>
<a href="reg.php">Create account...?</a>
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html><file_sep><?php
$uname="";
$err_uname="";
$pass="";
$err_pass="";
$hasError=false;
$username="root";
$servername="localhost";
$password="";
$db_name="mydb";
if(isset($_POST["ok"])){
//USERNAME VALIDATION
if(empty($_POST["uname"])){
$err_uname="Username Required";
$hasError =true;
}
elseif((strlen($_POST["uname"])<6)){
$err_uname="Username must be 6 characters long!";
$hasError=true;
}
else{
$uname = htmlspecialchars($_POST["uname"]);
}
//PASSWORD VALIDATION
if(empty($_POST["pass"])){
$err_pass="Please Enter Password!";
$hasError=true;
}
elseif(strlen($_POST["pass"])<8){
$err_pass="Password must be 8 characters long.";
$hasError=true;
}
elseif(!strpos($_POST['pass'], "1") && !strpos($_POST['pass'], "2") && !strpos($_POST['pass'], "3") && !strpos($_POST['pass'], "4")
&& !strpos($_POST['pass'], "5") && !strpos($_POST['pass'], "6") && !strpos($_POST['pass'], "7") && !strpos($_POST['pass'], "8")
&& !strpos($_POST['pass'], "9") && !strpos($_POST['pass'], "0")) {
$err_pass="Password must have 1 numeric";
$hasError=true;
}
elseif(strcmp(strtoupper($_POST["pass"]),$_POST["pass"])==0 && strcmp(strtolower($_POST["pass"]),$_POST["pass"])==0){
$err_pass="Password must contain 1 Upper and Lowercase letter.";
$hasError=true;
}
elseif(strpos($_POST["pass"],"#")==false && strpos($_POST["pass"],"?")==false){
$err_pass="Password must contain '#' or '?'.";
$hasError=true;
}
else{
$pass=htmlspecialchars($_POST["pass"]);
}
if(!$hasError){
$conn = mysqli_connect($servername,$username,$password,$db_name);
if(!$conn){
die("Connection failed: " .mysqli_connect_error());
}
mysqli_query($conn,"INSERT INTO user(id,username,password,usertype) VALUES('1234','$uname','$pass','user')");
header("Location: login.php");
}
}
?><file_sep><?php
$err_name="";
$err_uname = "";
$err_pass = "";
$err_cpass = "";
$err_gender = "";
$errMail = "";
$err_contact = "";
$r = "required*";
$has_err = false;
if (isset($_POST["ok"])) {
if(empty($_POST["fname"])) {
$err_name = $r;
$has_err = true;
}
if (empty($_POST["uname"])) {
$err_uname = $r;
$has_err = true;
}
if (empty($_POST["pass"])) {
$err_pass = $r;
$has_err = true;
}
else if (strlen($_POST["pass"]) < 8) {
$err_pass = "Password must be <PASSWORD>";
$has_err = true;
}
else {
if (empty($_POST["cpass"])) {
$err_cpass = $r;
$has_err = true;
}
else if ($_POST["cpass"] != $_POST["pass"]) {
$err_cpass = "[Password and confirm password must be same";
$has_err = true;
}
}
if (empty($_POST["gender"])) {
$err_gender = $r;
$has_err = true;
}
if (empty($_POST["email"])) {
$errMail = "Mail address required*";
}
else if (strlen(strpos($_POST["email"] , "@")) > 0 && strlen(strpos($_POST["email"], ".")) > 0) {
if (strpos($_POST["email"] , "@") > strrpos($_POST["email"], ".")) {
$errMail = "Invalid mail format [wrong placcement]";
}
else $mail = htmlspecialchars($_POST["email"]);
}
else $errMail = "Invalid mail format [Missing characters]";
if (empty($_POST["address"])) {
$address = "Address required*";
}
if (empty($_POST["phn"])) {
$has_err = true;
$err_contact = $r;
}
else if (!is_numeric($_POST["phn"])) {
$has_err = true;
$err_contact = "Cantact number does not contain characters";
}
}
if (!$has_err && isset($_POST["ok"])) {
$newChild = simplexml_load_file("admins.xml");
$child = $newChild->addChild("admin");
$child->addChild("fullName", $_POST["fname"]);
$child->addChild("userName", $_POST["uname"]);
$child->addChild("password", $_POST["<PASSWORD>"]);
$child->addChild("gender", $_POST["gender"]);
$child->addChild("mail", $_POST["email"]);
$child->addChild("contact", $_POST["phn"]);
$child->addChild("city", $_POST["city"]);
$file = fopen("admins.xml", "w");
fwrite($file, $newChild->saveXML());
header("Location: login.php");
}
?><file_sep><?php include_once "php_code/login_validation.php" ;?>
<html>
<head>
<title>KENAKATA SUPERSHOP</title>
</head>
<body>
<center><h1>Login</h1></center>
<center>
<form action="" method="POST">
<table>
<tr>
<td align="left" style="font-size: 30px;"><span style="color:white;">User Name:</span></td>
<td align="left"><input type="text" placeholder="User Name..." value="<?php echo $uname;?>" name="uname"></td>
<td align="left"><span style="color:white;">*<?php echo $err_uname;echo $err_msg;?></span></td>
</tr>
<tr>
<td align="left" style="font-size: 30px;"><span style="color:white;">Password:</span></td>
<td align="left"><input type="password" placeholder="Password..." value="<?php echo $pass;?>" name="pass"></td>
<td align="left"><span style="color:white;">*<?php echo $err_pass;?></span></td>
</tr>
<tr>
<td style="font-size: 22px;"><a href="registration.php"><u>Create an account?</u></a></td>
<td align="right" >
<input type="submit" name="login" value="Login">
</td>
</tr>
</table>
</form>
</center>
</header>
</body>
</html><file_sep><?php
require "validate_registration.php";
?>
<html>
<head>
<title>Registration</title>
</head>
<body>
<form action="" method="post" style="width: 700px;">
<fieldset style="background-color: lightgray;">
<table align="center">
<h1 align="center">Welcome to Registration.</h1>
<tr style="line-height: 60px;">
<td align="right">
Full Name:
</td>
<td>
<input type="text" name="fname">
<span> <?php echo "$err_name"; ?> </span>
</td>
<tr style="line-height: 60px;">
<td align="right">
User Name:
</td>
<td>
<input type="text" name="uname">
<span> <?php echo "$err_uname"; ?> </span>
</td>
</tr>
<tr style="line-height: 60px;">
<td align="right">
Password:
</td>
<td>
<input type="Password" name="pass">
<span> <?php echo "$err_pass"; ?> </span>
</td>
</tr>
<tr style="line-height: 60px;">
<td align="right">
Confirm Password:
</td>
<td>
<input type="Password" name="cpass">
<span> <?php echo "$err_cpass"; ?> </span>
</td>
</tr>
<tr style="line-height: 60px;">
<td align="right">
Gender:
</td>
<td>
<input type="radio" name="gender">Male  
<input type="radio" name="gender">Female
<span> <?php echo "      $err_gender"; ?> </span>
</td>
</tr>
<tr style="line-height: 60px;">
<td align="right">
E-mail Address:
</td>
<td>
<input type="text" name="email">
<span> <?php echo "$errMail"; ?> </span>
</td>
</tr>
<tr style="line-height: 60px;">
<td align="center">
Contact No..
</td>
<td>
<input type="text" name="phn">
<span> <?php echo "$err_contact"; ?> </span>
</td>
</tr>
<tr style="line-height: 60px;">
<td align="right">
City:
</td>
<td>
<select name="city">
<option>Noakhali</option>
<option>Dhaka</option>
<option>Barishal</option>
</select>
</td>
</tr>
<tr style="line-height: 60px;">
<td colspan="2" align="center">
<input type="submit" name="ok" value="OK">
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html><file_sep><?php
if (isset[$_POST["submit"]]) {
}
}
?>
<html>
<title>Add Book</title>
<body>
<form action="" method="post">
<table style="background-color: lightgray; width: 200px;">
<tr>
<td>
<img src="resources/book.jpg">
<h1 align="center">Add a Book</h1>
</td>
</tr>
<tr>
<td>
Book Name
</td>
</tr>
<tr>
<td>
<input type="text" name="name">
</td>
</tr>
<tr>
<td>
Category
</td>
</tr>
<tr>
<td>
<select name="category">
<option>Nobel</option>
<option>Science fiction</option>
<option>Literature</option>
</select>
</td>
</tr>
<tr>
<td>
Description
</td>
</tr>
<tr>
<td>
<textarea name="description"></textarea>
</td>
</tr>
<tr>
<td>
Edition
</td>
</tr>
<tr>
<td>
<input type="text" name="edition">
</td>
</tr>
<tr>
<td>
ISBN
</td>
</tr>
<tr>
<td>
<input type="text" name="isbn">
</td>
</tr>
<tr>
<td>
pages
</td>
</tr>
<tr>
<td>
<input type="text" name="page">
</td>
</tr>
<tr>
<td>
price
</td>
</tr>
<tr>
<td>
<input type="text" name="price">
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit">
</td>
</tr>
</table>
</form>
</body>
</html><file_sep><?php
$err_name = "";
$err_pass = "";
$has_err = false;
if (isset($_POST["login"])) {
if (empty($_POST["uname"])) {
$has_err = true;
$err_name = "Required*";
}
if (empty($_POST["pass"])) {
$has_err = true;
$err_pass = "<PASSWORD>*";
}
}
if (isset($_POST["login"]) && !$has_err) {
$checkList = simplexml_load_file("admins.xml");
$checkList = $checkList->admin;
$is_success = false;
foreach ($checkList as $i) {
echo "$i->userName $i->password<br>";
if ($i->userName == $_POST["uname"] && $i->password == $_POST["pass"]) {
$is_success = true;
}
}
if ($is_success == false) {
echo "Wrong username or password";
}
else {
setcookie("username", $_POST["uname"], time() + 3600);
header("Location: dashboard.php");
}
}
else echo $has_err;
?>
|
19572a85c4434a06443b066403bcd236d399bf87
|
[
"PHP"
] | 12
|
PHP
|
Shashwata-Dey/webtech_php
|
af32a6df1b9757f52616c242431128023f0b39c3
|
ad9f0a369cce56ec6fb5f3685cdc93baa96a4e16
|
refs/heads/master
|
<file_sep># faktory_worker_node
[](https://travis-ci.org/jbielick/faktory-client)
[](https://coveralls.io/github/jbielick/faktory_worker_node)


[](https://www.npmjs.com/package/faktory-worker)
This repository provides a client and node worker framework for [Faktory](https://github.com/contribsys/faktory). The client allows you to push jobs and communicate with the Faktory server and the worker process fetches background jobs from the Faktory server and processes them.
Faktory server compatibility: v0.6.0
## Installation
```
npm install faktory-worker
```
## Usage
### Pushing jobs
```js
const faktory = require('faktory-worker');
const client = await faktory.connect();
const jid = await client.push({
jobtype: 'MyDoWorkJob',
args: [3, 'small']
});
await client.close();
```
A job is a payload of keys and values according to [the faktory job payload specification](https://github.com/contribsys/faktory/wiki/The-Job-Payload). Any keys provided will be passed to the faktory server during `PUSH`. A `jid` (uuid) is created automatically for your job when using this library. See [the spec](https://github.com/contribsys/faktory/wiki/The-Job-Payload) for more options and defaults.
### Processing jobs
```js
const faktory = require('faktory-worker');
faktory.register('MyDoWorkJob', async (id, size) => {
const img = await Image.find(id);
await resize(img.blob, size);
});
await faktory.work();
// send INT signal to shutdown gracefully
```
A job function can be a sync or async function. Simply return a promise or use `await` in your async function to perform async tasks during your job. If you return early or don't `await` properly, the job will be `ACK`ed when the function returns.
`faktory.work()` traps `INT` and `TERM` signals so that it can gracefully shut down and finish any in-progress jobs before the `options.timeout` is reached.
### Middleware
```js
const faktory = require('faktory-worker');
faktory.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.job.jobtype} took ${ms}ms`);
});
await faktory.work();
```
Faktory middleware works just like [`koa`](https://github.com/koajs/koa) middleware. You can register a middleware function (async or sync) with `.use`. Middleware is called for every job that is performed. Always return a promise, `await next()`, or `return next();` to allow execution to continue down the middleware chain.
### CLI
`faktory-worker` comes with two helper scripts:
`node_modules/.bin/faktory-work`
Starts one worker. Use `--help` for more information.
and
`node_modules/.bin/faktory-cluster`
### Debugging
Use `DEBUG=faktory*` to see related debug log lines.
## FAQ
* How do I specify the Faktory server location?
By default, it will connect to `tcp://localhost:7419`.
Use FAKTORY_URL to specify the URL, e.g. `tcp://faktory.example.com:12345` or use FAKTORY_PROVIDER to specify the environment variable which contains the URL: `FAKTORY_PROVIDER=FAKTORYTOGO_URL`. This level of
indirection is useful for SaaSes, Heroku Addons, etc.
* How do I access the job payload in my function?
The function passed to `register` can be a thunk. The registered function will receive the job `args` and if that function returns a function, that returned function will be called and provided the raw `job` payload containing all custom props and other metadata of the job payload.
```js
faktory.register('JobWithHeaders', (...args) => async (job) => {
const [ email ] = args;
I18n.locale = job.custom.locale;
log(job.custom.txid);
await sendEmail(email);
});
```
## TODO
- [ ] Handle signals from server heartbeat response
- [ ] Require jobs from folder and automatically register
- [ ] Logging
- [x] Middleware
- [x] CLI
- [x] Heartbeat
- [x] Tests
- [x] Authentication
- [x] Fail jobs
- [x] Add'l client commands API
- [x] Labels
## Development
Install docker.
`bin/server` will run the faktory server in a docker container. The server is available at `localhost:7419`
Use `DEBUG=faktory*` to see debug lines.
## Author
<NAME>, @jbielick
<file_sep>const debug = require('debug')('faktory-worker:test-helper');
const {
queueName,
withConnection,
mockedServer,
mocked
} = require('faktory-client/test/support/helper');
const sleep = (ms, value = true) => {
return new Promise(resolve => setTimeout(() => resolve(value), ms));
};
const push = async (opts = {}) => {
const queue = opts.queue || queueName();
const jobtype = 'TestJob';
const args = opts.args || [];
const jid = await withConnection(async (client) => {
return client.push({
jobtype,
queue,
args
});
});
return { queue, jobtype, args, jid };
};
module.exports = {
sleep,
push,
mockedServer,
mocked
};
<file_sep>0.8.0 | 2018-03-24
---
* Upgrade faktory-client to `v0.6.0`
* FAKTORY_URL is parsed by URL lib—must contain protocol `tcp://` where it previously did not
0.7.0 | 2018-02-05
---
* Upgrade faktory-client to `v0.5.0`
* Run tests against faktory `v0.7.0`
* Allow `options.heartbeatInterval` override (default 15s)
* Gracefully reconnect when connections are interrupted / closed
0.6.3 | 2017-11-19
---
* Allow jobs to reject and FAIL with a string or undefined (without an error object). [#2](https://github.com/jbielick/faktory_worker_node/issues/2)
0.6.2 | 2017-11-12
---
* Upgrade faktory-client to `v0.4.2`
0.6.1 | 2017-11-12
---
* Check job timeout completion more frequently
0.6.0 | 2017-11-12
---
* Upgrade faktory-client for faktory protocol version 2
* BUGFIX: don't try to execute jobs that aren't dispatched
* Interpret heartbeat response for quiet|terminate
* Fix race condition in which graceful shutdown drains the pool too early and prevents the processor from ACKing of FAILing a job
* Heartbeat now occurs only for the manager, not for every processor and connection in the pool.
* Tests now run in parallel; faktory is not spawned by node. The faktory server must be started before running the tests. Use bin/server for convenience.
0.5.0 | 2017-11-11
---
* Shuffle the queues array to prevent queue starvation
0.4.1 | 2017-11-11
---
* Throwing / propagating errors during .execute() was causing some stabilities issues when shutting down the process. I believe this was interrupting with the normal work .loop() and preventing graceful shutdown. Ideally, the errors thrown in jobs are propagated to the application code in an emitter or registered callback (e.g. errorCallbacks << () => { ... }) so applications can send those errors to a reporting service. Until then, the error is logged to console.error instead of thrown. The same applies for dispatching.
0.4.0 | 2017-11-11
---
* Based on the discussion in gitter, it became evident that a best practice for throughput was to create a pool of connections equal to the desired concurrency. This didn't produce fruitful results at first, but the introduction of a Processor pool within the Manager with a connection pool of TCP sockets to the faktory server produced some substantial (2x+) improvements to throughput and some pieces of the code became easier to reason about.
Prior to this work:
Concurrency: 20
Duration: 4.639131743s
Jobs/s: 6467
With Processor Pool:
Concurrency: 20
Duration: 3.31144746s
Jobs/s: 9059
- *benchmarking was done by running faktory directly, not through docker*
* Introduce Processor pool (w/ connection pool) within Manager: the number of TCP connections to the faktory server will now be equal to the concurrency setting (default 20).
* benchmark scripts added
0.3.0 | 2017-11-01
---
* Add heartbeat
* Allow `concurrency` option in constructor, CLI
0.2.6 | 2017-10-28
---
* .stop() waits for the in-progress job to complete before timeout
* Upgrades `faktory-client` dependency to 0.2.2
0.2.5 | 2017-10-28
---
* Upgrades faktory-client to 0.2.1
0.2.4 | 2017-10-28
---
* Shutdown gracefully via .stop()
0.2.0 | 2017-10-28
---
* Extact client code to `faktory-client` package
* Add TravisCI
* Use async/await
* Tests for manager.js
* add ava for tests, nyc for coverage
|
9e75014020c04912934756c9272f571bd8575cb5
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
tbonz/faktory_worker_node
|
79cc9af07741e70a53c296e20a5378f3c5acde91
|
c9b920a7dfdd84b8fa34156e0b8e9a783f14a2c4
|
refs/heads/master
|
<repo_name>Mahek1258/p-30-box-game-2<file_sep>/sketch.js
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
const Constraint = Matter.Constraint;
var stand1;
var box1,box2,box3,box4,box5,box6,box7,box8,box9,box10,box11,box12,box13,box14,box15;
var ball,slingshot;
var score = 0 ;
function preload()
{
}
function setup() {
createCanvas(800, 700);
engine = Engine.create();
world = engine.world;
//Create the Bodies Here.
stand1 = new Ground(450,680,600,20);
//lowest layer
box1 = new Box(250,600,70,70);
box2 = new Box(350,600,70,70);
box3 = new Box(450,600,70,70);
box4 = new Box(550,600,70,70);
box5 = new Box(650,600,70,70);
//second layer
box6 = new Box(300,530,70,70);
box7 = new Box(400,530,70,70);
box8 = new Box(500,530,70,70);
box9 = new Box(600,530,70,70);
//third layer
box10 = new Box(350,460,70,70);
box11 = new Box(450,460,70,70);
box12 = new Box(550,460,70,70);
//forth layer
box13 = new Box(400,390,70,70);
box14 = new Box(500,390,70,70);
//sixth layer
box15 = new Box(450,320,70,70);
ball = new Ball(100,350,50);
slingshot = new SlingShot(ball.body,{x:100, y:350});
Engine.run(engine);
}
function draw() {
Engine.update(engine);
background(0);
stand1.display();
box1.display();
box2.display();
box3.display();
box4.display();
box5.display();
box6.display();
box7.display();
box8.display();
box9.display();
box10.display();
box11.display();
box12.display();
box13.display();
box14.display();
box15.display();
ball.display();
slingshot.display();
}
function keyPressed(){
if(keyCode===32){
Ball.attach();
}
}
function mouseDragged(){
Matter.Body.setPosition(ball.body, {x: mouseX , y: mouseY});
}
function mouseReleased(){
slingshot.fly();
}
|
3957842f32f63f69ebbcf43a640e92d02bdca21f
|
[
"JavaScript"
] | 1
|
JavaScript
|
Mahek1258/p-30-box-game-2
|
bcaf6418508bac06316ca4f60b74a7d337ab6f60
|
7322dcb9bf77ce4c8187b3ae7e687edfeae43e25
|
HEAD
|
<file_sep>var content = document.getElementById('content');
var image = document.createElement("img");
image.src = "img/" + "one" + "/" + 99 + ".jpg";
content.appendChild(image);
image.onerror = function() {
content.removeChild(image);
};
addAllPics(content, "talking");
addAllPics(content, "one");
addAllPics(content, "two");
addAllPics(content, "three");
addAllPics(content, "four");
function addAllPics(divName, folderName) {
var stillAdding = true;
var row = document.createElement("div");
row.className = "row";
divName.appendChild(row);
for (var i = 1; i < 12; i++) {
var image = document.createElement("img");
image.src = "img/" + folderName + "/" + i + ".jpg";
image.className = "img img-responsive";
var col = document.createElement("div");
col.className = "col-xs-4";
col.appendChild(image);
row.appendChild(col);
image.onerror = function() {
image.remove();
};
}
}
|
6b1f8e94eef9c1796ef960af96eb2d898f5ef1de
|
[
"JavaScript"
] | 1
|
JavaScript
|
Piejak/lexi
|
0a678d86d09924abf4ea89ebf3b428ce7e705ace
|
e05acc2bd18d1351ae0b1de4a57c480ee4bf1e67
|
refs/heads/master
|
<repo_name>asdoc/decision_tree_project<file_sep>/q02_decision_regressor_plot/build.py
# %load q02_decision_regressor_plot/build.py
# default imports
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_csv('./data/house_pricing.csv')
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=9)
depth_list = [2, 8, 10, 15, 20, 25, 30, 35, 45, 50, 80]
def decision_regressor_plot(X_train, X_test, y_train, y_test, depths):
train_scores = []
test_scores = []
for depth in depths:
model = DecisionTreeRegressor(criterion='mse', max_depth=depth, random_state=9)
model = model.fit(X_train, y_train)
y_pred_train = model.predict(X_train)
mse_train = mean_squared_error(y_pred_train, y_train)
train_scores.append(mse_train)
y_pred_test = model.predict(X_test)
mse_test = mean_squared_error(y_pred_test, y_test)
test_scores.append(mse_test)
plt.plot(depth_list, train_scores)
plt.plot(depth_list, test_scores)
plt.show()
|
42be964b2b905477974e66948aeee644bfc6997c
|
[
"Python"
] | 1
|
Python
|
asdoc/decision_tree_project
|
c581e4b23cd62231c61408f07fc81c1531fb69f4
|
875a608d78122c7491ac5b554936fc55881f3a93
|
refs/heads/master
|
<repo_name>yarbsemaj/SaveTheChange<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
})->name("welcome");
Route::get('/login', 'OauthController@authorise');
Route::post('/logout', function () {
session()->remove("user_id");
return redirect(route("welcome"));
})->name("logout");
Route::get('/home', function () {
return view("home");
});
Route::get('api/callback', 'OauthController@authorise');
<file_sep>/app/Helpers/Oauth.php
<?php
if (!function_exists('getProvider')) {
function getProvider()
{
return new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => env("clientId"), // The client ID assigned to you by the provider
'clientSecret' => env("clientSecret"), // The client password assigned to you by the provider
'urlAuthorize' => env("authURL"),
'urlAccessToken' => env("apiURL") . '/oauth/access-token',
'urlResourceOwnerDetails' => env("apiURL") . '/api/v1/me',
'redirectUri' => "http://savethechange.yarbsemaj.com/api/callback"
]);
}
}
if (!function_exists('refreshToken')) {
function refreshToken(\League\OAuth2\Client\Token\AccessToken $existingAccessToken, $userID)
{
if ($existingAccessToken->hasExpired()) {
$newAccessToken = getProvider()->getAccessToken('refresh_token', [
'refresh_token' => $existingAccessToken->getRefreshToken()
]);
$user = \App\StarlingUser::findOrFail($userID);
$user->access_token = $newAccessToken->getToken();
$user->refresh_token = $newAccessToken->getRefreshToken();
$user->expires_at = $newAccessToken->getExpires();
$user->save();
return $newAccessToken;
}
return $existingAccessToken;
}
}
if (!function_exists('getAccessToken')) {
function getAccessToken($userID)
{
$user = \App\StarlingUser::find($userID);
return refreshToken(new \League\OAuth2\Client\Token\AccessToken($user->toArray()), $userID);
}
}
if (!function_exists('apiRequest')) {
function apiRequest($accessToken, $url, $method, $options = [])
{
$provider = getProvider();
$request = $provider->getAuthenticatedRequest(
$method,
env("apiURL") . $url,
$accessToken,
$options
);
return $provider->getParsedResponse($request);
}
}
if (!function_exists('apiRequestForCurrentUser')) {
function apiRequestForCurrentUser($url, $method, $options = [])
{
$provider = getProvider();
$request = $provider->getAuthenticatedRequest(
$method,
env("apiURL") . $url,
getAccessToken(session()->get("user_id")),
$options);
return $provider->getParsedResponse($request);
}
}
if (!function_exists('validateUserCurrentUser')) {
function validateUserCurrentUser()
{
if (!session()->has("user_id")) return false;
$accessToken = getAccessToken(session()->get("user_id"));
if (!getProvider()->getResourceOwner($accessToken)->toArray()["authenticated"]) return false;
return true;
}
}
if (!function_exists('getCurrentUser')) {
function getCurrentUser()
{
return \App\StarlingUser::find(session()->get("user_id"));
}
}
<file_sep>/app/StarlingUser.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class StarlingUser extends Model
{
protected $fillable = ["customer_uid", "access_token", "refresh_token", "expires_at"];
protected $appends = array('expires');
public function getExpiresAttribute()
{
return $this->expires_at;
}
public function getNameAttribute()
{
$data = apiRequest(getAccessToken($this->id), "/api/v1/customers", "GET");
return $data["firstName"] . " " . $data["lastName"];
}
public function getGoalsAttribute()
{
$data = apiRequest(getAccessToken($this->id), "/api/v1/savings-goals", "GET");
return $data;
}
}
<file_sep>/app/Http/Controllers/OauthController.php
<?php
namespace App\Http\Controllers;
use App\StarlingUser;
class OauthController extends Controller
{
protected $provider;
public function __construct()
{
$this->provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => env("clientId"), // The client ID assigned to you by the provider
'clientSecret' => env("clientSecret"), // The client password assigned to you by the provider
'urlAuthorize' => env("authURL"),
'urlAccessToken' => env("apiURL") . '/oauth/access-token',
'urlResourceOwnerDetails' => env("apiURL") . '/api/v1/me',
'redirectUri' => "http://savethechange.yarbsemaj.com/api/callback"
]);
}
public function authorise()
{
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
$authorizationUrl = $this->provider->getAuthorizationUrl();
session()->put("oauth2state", $this->provider->getState());
header('Location: ' . $authorizationUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || (session()->has("oauth2state") && $_GET['state'] !== session()->get("oauth2state"))) {
if (session()->has("oauth2state"))
session()->remove('oauth2state');
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $this->provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo 'Access Token: ' . $accessToken->getToken() . "<br>";
echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $this->provider->getResourceOwner($accessToken);
$user = StarlingUser::updateOrCreate(
[
"customer_uid" => $resourceOwner->toArray()['customerUid']
],
[
"access_token" => $accessToken->getToken(),
"refresh_token" => $accessToken->getRefreshToken(),
"expires_at" => $accessToken->getExpires()
]);
session()->put("user_id", $user->id);
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
print_r($e->getResponseBody());
// Failed to get the access token or user details.
exit($e->getMessage());
}
}
}
}
|
bc09b42f19b47e1ee9ccc8a62fc0db246d08953d
|
[
"PHP"
] | 4
|
PHP
|
yarbsemaj/SaveTheChange
|
f26f0c16c55249c7eb46e4c1d3043adca64f54be
|
ba07103b2ac871715cea246fb9de36f38c82aa3b
|
refs/heads/master
|
<file_sep>#ifndef SUM_H
#define SUM_H
float sum(float a, float b);
#endif
<file_sep>#include <iostream>
#include "add.h"
float sum(float a, float b)
{
std::cout <<" Called sum with " << a << " and " << b << std::endl;
float s = add(a, b);
return(s);
}
<file_sep>
all: compile_add compile_sum compile_exec
compile_add: ./add/add.cpp
@echo "Step 01 - add.."
g++ -c ./add/add.cpp -o ./add/add.o -I/add
g++ -dynamiclib -o ./add/libadd.dylib ./add/add.o
@echo "-------------------------------------------------------"
compile_sum: ./sum/sum.cpp
@echo "Step 02 - add.."
g++ -c ./sum/sum.cpp -o ./sum/sum.o -I./sum -I./add
g++ -dynamiclib -o ./sum/libsum.dylib ./sum/sum.o -L./add -ladd
@echo "-------------------------------------------------------"
compile_exec: ./sum/sum.cpp
@echo "Step 03 - executable.."
g++ -o test.exe test.cpp -I./sum -L./sum -lsum
@echo "-------------------------------------------------------"
clean:
rm ./add/add.o
rm ./sum/sum.o
rm ./sum/libsum.dylib
rm ./add/libadd.dylib
rm test.exe
<file_sep>#ifndef ADD_H
#define ADD_H
float add(float a, float b);
#endif
<file_sep>#include <iostream>
float add(float a, float b)
{
std::cout <<" Called add with " << a << " and " << b << std::endl;
float s = a+b;
return(s);
}
<file_sep>#include <iostream>
#include "sum.h"
int main()
{
float x = 2.0;
float y = 5.0;
float val = sum(x,y);
std::cout << "Calculated result " << val << std::endl;
return(0);
}
<file_sep># cpp
Purpose: Some clarity on dynamic linking on macOS, rpath(relative path), loader_path, executable path, LD_LIBRARY_PATH and DYLD_LIBRARY_PATH
I got some issues while using a Machine Learning library on my MacBook Pro, which keeps on failing for C++ dynamic linking errors. I thought to create this **practical** tutorial based on https://www.mikeash.com/pyblog/friday-qa-2009-11-06-linking-and-install-names.html
This will give you how to create library in C++, dynamically link to the executable and search paths on Mac.
```
System Version: macOS 10.13.2 (17C88)
Kernel Version: Darwin 17.3.0
```
1. Compile C++ codes - using
make -f makefile
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> make -f makefile
Step 01 - add..
g++ -c ./add/add.cpp -o ./add/add.o -I/add
g++ -dynamiclib -o ./add/libadd.dylib ./add/add.o
-------------------------------------------------------
Step 02 - add..
g++ -c ./sum/sum.cpp -o ./sum/sum.o -I./sum -I./add
g++ -dynamiclib -o ./sum/libsum.dylib ./sum/sum.o -L./add -ladd
-------------------------------------------------------
Step 03 - executable..
g++ -o test.exe test.cpp -I./sum -L./sum -lsum
-------------------------------------------------------
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test.exe
Called sum with 2 and 5
Called add with 2 and 5
Calculated result 7
```
2. Above produces two libraries libsum.dylib, libadd.dylib and test.exe
Note that libsum.dylib itself depends on libsum.dylib.
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L test.exe
test.exe:
./sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L ./sum/libsum.dylib
./sum/libsum.dylib:
./sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
./add/libadd.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L ./add/libadd.dylib
./add/libadd.dylib:
./add/libadd.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
```
3. I try here to tweak the paths and explore the dynamic loading mechanism.
```
jvsingh: ~/work/cpp/dynamic-lib-test -> mv test.exe ../
jvsingh: ~/work/cpp/dynamic-lib-test -> cd ../
jvsingh: ~/work/cpp -> ./test.exe
dyld: Library not loaded: ./sum/libsum.dylib
Referenced from: /Users/jvsingh/work/cpp/./test.exe
Reason: image not found
Abort trap: 6
```
###### Hacks using **install_name_tool** to change the names of loaded libraries in the executable
```
jvsingh: ~/work/cpp -> otool -L test.exe
test.exe:
./sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/cpp -> install_name_tool -change "./sum/libsum.dylib" "./dynamic-lib-test/sum/libsum.dylib" test.exe
jvsingh: ~/work/cpp -> otool -L test.exe
test.exe:
./dynamic-lib-test/sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/cpp -> ./test.exe
dyld: Library not loaded: ./add/libadd.dylib
Referenced from: /Users/jvsingh/work/cpp/dynamic-lib-test/sum/libsum.dylib
Reason: image not found
Abort trap: 6
jvsingh: ~/work/cpp -> otool -L ./dynamic-lib-test/sum/libsum.dylib
./dynamic-lib-test/sum/libsum.dylib:
./sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
./add/libadd.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/cpp -> install_name_tool -change "./add/libadd.dylib" "./dynamic-lib-test/./add/libadd.dylib" ./dynamic-lib-test/sum/libsum.dylib
jvsingh: ~/work/cpp -> otool -L ./dynamic-lib-test/sum/libsum.dylib
./dynamic-lib-test/sum/libsum.dylib:
./sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
./dynamic-lib-test/./add/libadd.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/cpp -> ./test.exe
Called sum with 2 and 5
Called add with 2 and 5
Calculated result 7
```
##### It can be resolved using DYLD_LIBRARY_PATH
(Also note that LD_LIBRARY_PATH had no effect)
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> make -f makefile
Step 01 - add..
g++ -c ./add/add.cpp -o ./add/add.o -I/add
g++ -dynamiclib -o ./add/libadd.dylib ./add/add.o
-------------------------------------------------------
Step 02 - add..
g++ -c ./sum/sum.cpp -o ./sum/sum.o -I./sum -I./add
g++ -dynamiclib -o ./sum/libsum.dylib ./sum/sum.o -L./add -ladd
-------------------------------------------------------
Step 03 - executable..
g++ -o test.exe test.cpp -I./sum -L./sum -lsum
-------------------------------------------------------
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv test.exe ../
jvsingh: ~/work/github/cpp/dynamic-lib-test -> cd ../
jvsingh: ~/work/github/cpp -> otool -L test.exe
test.exe:
./sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp -> ./test.exe
dyld: Library not loaded: ./sum/libsum.dylib
Referenced from: /Users/jvsingh/work/github/cpp/./test.exe
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp -> export LD_LIBRARY_PATH=~/work/github/cpp/dynamic-lib-test/sum
jvsingh: ~/work/github/cpp -> ./test.exe
dyld: Library not loaded: ./sum/libsum.dylib
Referenced from: /Users/jvsingh/work/github/cpp/./test.exe
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp -> export DYLD_LIBRARY_PATH=~/work/github/cpp/dynamic-lib-test/sum
jvsingh: ~/work/github/cpp -> ./test.exe
dyld: Library not loaded: ./add/libadd.dylib
Referenced from: /Users/jvsingh/work/github/cpp/dynamic-lib-test/sum/libsum.dylib
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp -> export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:/Users/jvsingh/work/github/cpp/dynamic-lib-test/add
jvsingh: ~/work/github/cpp -> ./test.exe
Called sum with 2 and 5
Called add with 2 and 5
Calculated result 7
jvsingh: ~/work/github/cpp ->
```
### Using Executable path
compile using makefile.executable_path
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> make -f makefile.executable_path
Step 01 - add..
g++ -c ./add/add.cpp -o ./add/add.o -I/add
g++ -dynamiclib -o ./add/libadd.dylib ./add/add.o -install_name @executable_path/lib/libadd.dylib
-------------------------------------------------------
Step 02 - add..
g++ -c ./sum/sum.cpp -o ./sum/sum.o -I./sum -I./add
g++ -dynamiclib -o ./sum/libsum.dylib ./sum/sum.o -L./add -ladd -install_name @executable_path/lib/libsum.dylib
-------------------------------------------------------
Step 03 - executable..
g++ -o test.exe test.cpp -I./sum -L./sum -lsum
-------------------------------------------------------
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
```
Dependency :
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L test.exe
test.exe:
@executable_path/lib/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test.exe
dyld: Library not loaded: @executable_path/lib/libsum.dylib
Referenced from: /Users/jvsingh/work/github/cpp/dynamic-lib-test/./test.exe
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
```
#### Move the libsum into desired folder:
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv ./sum/libsum.dylib ./lib/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test.exe
dyld: Library not loaded: @executable_path/lib/libadd.dylib
Referenced from: /Users/jvsingh/work/github/cpp/dynamic-lib-test/./lib/libsum.dylib
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
```
##### Now, the complaint for libadd.dylib (libsum.dylib depends on libadd.dylib).
#### Move libadd as well -
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv ./add/libadd.dylib ./lib/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test.exe
Called sum with 2 and 5
Called add with 2 and 5
Calculated result 7
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
```
#### Lets move whole structure to a new location:
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test1/test2/test.exe
dyld: Library not loaded: @executable_path/lib/libsum.dylib
Referenced from: /Users/jvsingh/work/github/cpp/dynamic-lib-test/./test1/test2/test.exe
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv lib test1/test2/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test1/test2/test.exe
Called sum with 2 and 5
Called add with 2 and 5
Calculated result 7
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
```
So we see above that how @executable_path works.
### LOADER PATH method
Note below that libadd.dylib is loaded by sum/libsum.dylib so we have relative path wrt this library as @loader_path/../add/libadd.dylib
similarly libsum.dylib is loaded by test.exe , sp we have loader path
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> make -f makefile.loader_path
Step 01 - add..
g++ -c ./add/add.cpp -o ./add/add.o -I/add
g++ -dynamiclib -o ./add/libadd.dylib ./add/add.o -install_name @loader_path/../add/libadd.dylib
-------------------------------------------------------
Step 02 - add..
g++ -c ./sum/sum.cpp -o ./sum/sum.o -I./sum -I./add
g++ -dynamiclib -o ./sum/libsum.dylib ./sum/sum.o -L./add -ladd -install_name @loader_path/sum/libsum.dylib
-------------------------------------------------------
Step 03 - executable..
g++ -o test.exe test.cpp -I./sum -L./sum -lsum
-------------------------------------------------------
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L test.
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/objdump: 'test.': No such file or directory
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L test.exe
test.exe:
@loader_path/sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L ./sum/libsum.dylib
./sum/libsum.dylib:
@loader_path/sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
@loader_path/../add/libadd.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L ./add/libadd.dylib
./add/libadd.dylib:
@loader_path/../add/libadd.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test.exe
Called sum with 2 and 5
Called add with 2 and 5
Calculated result 7
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
```
Lets change relative positions, It works :
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mkdir -p test1/test2/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mkdir -p test1/test2/sum
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mkdir -p test1/test2/add
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv test.exe test1/test2/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv ./sum/libsum.dylib test1/test2/sum/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv ./add/libadd.dylib test1/test2/add/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test1/test2/test.exe
Called sum with 2 and 5
Called add with 2 and 5
Calculated result 7
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
```
As expected, the below fails - when paths are distrubed
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv test1/test2/add test1/test2/fff
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test1/test2/test.exe
dyld: Library not loaded: @loader_path/../add/libadd.dylib
Referenced from: /Users/jvsingh/work/github/cpp/dynamic-lib-test/./test1/test2/sum/libsum.dylib
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
```
### RPATH Method
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> make -f makefile.rpath
Step 01 - add..
g++ -c ./add/add.cpp -o ./add/add.o -I/add
g++ -dynamiclib -o ./add/libadd.dylib ./add/add.o -install_name @rpath/add/libadd.dylib
-------------------------------------------------------
Step 02 - add..
g++ -c ./sum/sum.cpp -o ./sum/sum.o -I./sum -I./add
g++ -dynamiclib -o ./sum/libsum.dylib ./sum/sum.o -L./add -ladd -install_name @rpath/sum/libsum.dylib
-------------------------------------------------------
Step 03 - executable..
g++ -o test.exe test.cpp -I./sum -L./sum -lsum -rpath @executable_path/../../cpp/dynamic-lib-test
-------------------------------------------------------
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L test.exe
test.exe:
@rpath/sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L ./sum/libsum.dylib
./sum/libsum.dylib:
@rpath/sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
@rpath/add/libadd.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L ./add/libadd.dylib
./add/libadd.dylib:
@rpath/add/libadd.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test.exe
Called sum with 2 and 5
Called add with 2 and 5
Calculated result 7
```
#### Let us try moving executable to some complex relative paths deep inside
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mkdir -p test1/test2/test3/test4
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv test.exe test1/test2/test3/test4/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test1/test2/test3/test4/test.exe
dyld: Library not loaded: @rpath/sum/libsum.dylib
Referenced from: /Users/jvsingh/work/github/cpp/dynamic-lib-test/./test1/test2/test3/test4/test.exe
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mkdir -p ./test1/test2/test3/test4/sum
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv ./sum/libsum.dylib ./test1/test2/test3/test4/sum/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test1/test2/test3/test4/test.exe
dyld: Library not loaded: @rpath/sum/libsum.dylib
Referenced from: /Users/jvsingh/work/github/cpp/dynamic-lib-test/./test1/test2/test3/test4/test.exe
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ls -lrt ./test1/test2/test3/test4/../../cpp/dynamic-lib-test
ls: ./test1/test2/test3/test4/../../cpp/dynamic-lib-test: No such file or directory
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mkdir -p ./test1/test2/test3/test4/../../cpp/dynamic-lib-test
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mkdir -p ./test1/test2/test3/test4/../../cpp/dynamic-lib-test/sum
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv ./test1/test2/test3/test4/sum ./test1/test2/test3/test4/../../cpp/dynamic-lib-test/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ls -lrt ./test1/test2/test3/test4/../../cpp/dynamic-lib-test/*
total 32
-rwxr-xr-x 1 jvsingh staff 15924 Jun 11 19:46 libsum.dylib
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test1/test2/test3/test4/test.exe
dyld: Library not loaded: @rpath/add/libadd.dylib
Referenced from: /Users/jvsingh/work/github/cpp/dynamic-lib-test/test1/test2/cpp/dynamic-lib-test/sum/libsum.dylib
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp/dynamic-lib-test -> find ./test1/test2/test3/test4/
./test1/test2/test3/test4/
./test1/test2/test3/test4//test.exe
jvsingh: ~/work/github/cpp/dynamic-lib-test -> find ./test1/
./test1/
./test1//test2
./test1//test2/cpp
./test1//test2/cpp/dynamic-lib-test
./test1//test2/cpp/dynamic-lib-test/sum
./test1//test2/cpp/dynamic-lib-test/sum/libsum.dylib
./test1//test2/test3
./test1//test2/test3/test4
./test1//test2/test3/test4/test.exe
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mkdir -p ./test1//test2/cpp/dynamic-lib-test/add
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv ./add/libadd.dylib ./test1//test2/cpp/dynamic-lib-test/add/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test1/test2/test3/test4/test.exe
Called sum with 2 and 5
Called add with 2 and 5
Calculated result 7
jvsingh: ~/work/github/cpp/dynamic-lib-test ->
```
Note that rpath can also be resolved by **DYLD_LIBRARY_PATH**
```
jvsingh: ~/work/github/cpp/dynamic-lib-test -> make -f makefile.rpath
Step 01 - add..
g++ -c ./add/add.cpp -o ./add/add.o -I/add
g++ -dynamiclib -o ./add/libadd.dylib ./add/add.o -install_name @rpath/add/libadd.dylib
-------------------------------------------------------
Step 02 - add..
g++ -c ./sum/sum.cpp -o ./sum/sum.o -I./sum -I./add
g++ -dynamiclib -o ./sum/libsum.dylib ./sum/sum.o -L./add -ladd -install_name @rpath/sum/libsum.dylib
-------------------------------------------------------
Step 03 - executable..
g++ -o test.exe test.cpp -I./sum -L./sum -lsum -rpath @executable_path/../../cpp/dynamic-lib-test
-------------------------------------------------------
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L test.exe
test.exe:
@rpath/sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test -> otool -L ./sum/libsum.dylib ; otool -L ./add/libadd.dylib
./sum/libsum.dylib:
@rpath/sum/libsum.dylib (compatibility version 0.0.0, current version 0.0.0)
@rpath/add/libadd.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
./add/libadd.dylib:
@rpath/add/libadd.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.0.0)
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test.exe
Called sum with 2 and 5
Called add with 2 and 5
Calculated result 7
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mkdir -p test1/test2/test3/test4
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ls -lrt test1/test2/test3/test4
jvsingh: ~/work/github/cpp/dynamic-lib-test -> mv test.exe test1/test2/test3/test4/
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test1/test2/test3/test4/test.exe
dyld: Library not loaded: @rpath/add/libadd.dylib
Referenced from: /Users/jvsingh/work/github/cpp/dynamic-lib-test/sum/libsum.dylib
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp/dynamic-lib-test -> export DYLD_LIBRARY_PATH=/Users/jvsingh/work/github/cpp/dynamic-lib-test/sum
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test1/test2/test3/test4/test.exe
dyld: Library not loaded: @rpath/add/libadd.dylib
Referenced from: /Users/jvsingh/work/github/cpp/dynamic-lib-test/sum/libsum.dylib
Reason: image not found
Abort trap: 6
jvsingh: ~/work/github/cpp/dynamic-lib-test -> export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:/Users/jvsingh/work/github/cpp/dynamic-lib-test/add
jvsingh: ~/work/github/cpp/dynamic-lib-test -> ./test1/test2/test3/test4/test.exe
Called sum with 2 and 5
Called add with 2 and 5
Calculated result 7
jvsingh: ~/work/github/cpp/dynamic-lib-test -> echo $DYLD_LIBRARY_PATH
/Users/jvsingh/work/github/cpp/dynamic-lib-test/sum:/Users/jvsingh/work/github/cpp/dynamic-lib-test/add
```
So it works :)
|
ff1123a9f2f42eac3726c9bffba9429765deb407
|
[
"Markdown",
"C",
"Makefile",
"C++"
] | 7
|
C
|
jaivrat/cpp
|
86a15a66d8a1d6e81f225d79d7c99d3c548a4252
|
002ec17443cad140c1426b3c7252314a54a68dfb
|
refs/heads/master
|
<file_sep>
```{r}
library("rstan", quietly = T)
library("tidyverse", quietly = T)
library("magrittr", quietly = T)
##this is where the data is
URL <- "https://raw.githubusercontent.com/carlislerainey/priors-for-separation/master/br-replication/data/need.csv"
```
```{r}
##sy: this function automatically centers covariates. rstanarm has this function built into it already
autoscale <- function(x, center = TRUE, scale = TRUE) {
nvals <- length(unique(x))
if (nvals <= 1) {
out <- x
} else if (nvals == 2) {
out <- if (scale) {
(x - min(x, na.rm = TRUE)) / diff(range(x, finite = TRUE))
} else x
if (center) {
out <- x - mean(x)
}
} else {
out <- if (center) {
x - mean(x, na.rm = TRUE)
} else x
out <- if (scale) out / sd(out, na.rm = TRUE)
}
out
}
```
###Define model
```{r}
f <- (oppose_expansion ~ dem_governor + obama_win + gop_leg + percent_uninsured +
income + percent_nonwhite + percent_metro)
```
### Get data and set up
```{r}
br <- read_csv(URL) %>%
mutate(oppose_expansion = 1 - support_expansion,
dem_governor = -1 * gop_governor,
obama_win = as.integer(obama_share >= 0.5),
percent_nonwhite = percent_black + percent_hispanic)%>%
rename(gop_leg = legGOP) %>%
# keep only variables in the formula
model.frame(f, data = .) %>%
# drop missing values (if any?)
drop_na()
```
use the centering/standardizing function
```{r}
br_scaled <- br %>%
# Autoscale all vars but response
mutate_at(vars(-oppose_expansion), autoscale)
```
Run the simple GLM
```{r}
glm(f, data = br, family = "binomial") %>% summary()
```
Run the rstanarm model. This is a built in function that has a default prior. It automatically adjusts scale
```{r}
library("rstanarm") ##sy: has some stan glm functions
fit1<-stan_glm(f, data = br, family = "binomial")
fit2<-stan_glm(f, data = br, prior = NULL, family = "binomial")
summary(fit1)
help("prior_summary")
```
The GLM version includes priors, so the uncertainty decreases from the regular glm model
```{r}
library(bayesplot, quietly=T)
##fit1 had the prior
mcmc_dens(as.array(fit1), "dem_governor")
##fit2 ran w/o prior
mcmc_dens(as.array(fit2), "dem_governor")
```
The model w/o prior has much more extreme values and a larger distribution overall
<file_sep># Heteroskedasticity and Robust Regression
`r rpkg("VGAM")` is needed for the Laplace distribution.
```{r message=FALSE}
library("rubbish")
library("VGAM")
library("tidyverse")
library("rstan")
library("bayesplot")
```
## Linear Regression with Student t distributed errors
Like OLS, Bayesian linear regression with normally distributed errors is sensitive to outliers.
The normal distribution has narrow tail probabilities.
This plots the normal, Double Exponential (Laplace), and Student-t (df = 4) distributions all with mean 0 and scale 1, and the surprise ($- log(p)$) at each point.
Higher surprise is a lower log-likelihood.
Both the Student-t and Double Exponential distributions have surprise values well below the normal in the ranges (-6, 6).[^tailareas]
This means that outliers impose less of a penalty on the log-posterio models using these distributions, and the regression line would need to move less to incorporate those observations since the error distribution will not consider them as unusual.
##sy:we are fitting multiple bayesian models with different distributions as the priors as part of the 'robust regression' process: we want to see which distribution gives posterior predictions of our outcome that fits the data the best
[^tailareas]: The Double Exponential distribution still has a thinner tail than the Student-t at higher values.
```{r}
z <- seq(-6, 6, length.out = 100)
bind_rows(
tibble(z = z,
p = dnorm(z, 0, 1),
distr = "Normal"),
tibble(z = z,
p = dt(z, 4),
distr = "Student-t (df = 4)"),
tibble(z = z,
p = VGAM::dlaplace(z, 0, 1),
distr = "Double Exponential")) %>%
mutate(`-log(p)` = -log(p)) %>%
ggplot(aes(x = z, y = `-log(p)`, colour = distr)) +
geom_line()
```
```{r include=FALSe}
mod_t <- stan_model("stan/rlm.stan") ##just compiles the model, haven't given it any data
```
```{r}
unionization <- read_tsv("data/western1995/unionization.tsv",
col_types = cols(
country = col_character(),
union_density = col_double(),
left_government = col_double(),
labor_force_size = col_number(),
econ_conc = col_double()
))
mod_t_data <- lm_preprocess(union_density ~ left_government + log(labor_force_size) + econ_conc, data = unionization)
mod_data <- within(mod_t_data, {
b_loc <- 0
b_scale <- 100
sigma_scale <- sd(y)
})
```
```{r}
mod_data$X
```
The `max_treedepth` parameter needed to be increased because in some runs it was hitting the maximum treedepth.
This is likely due to the wide tails of the Student t distribution.
```{r}
mod_t_fit <- sampling(mod_t, data = mod_data, control = list(max_treedepth = 11))
```
```{r output=FALSE}
summary(mod_t_fit, pars = c("nu", "sigma", "b"))$summary
```
####Check out the bayesplot package, which
```{r}
mcmc_violin(as.array(mod_t_fit), regex_pars="b") ##a violin plot for each chain
mcmc_dens(as.array(mod_t_fit), regex_pars="b") ##posterior distribution of mcmc draws
stan_trace(mod_t_fit, pars="b")
mcmc_pairs(as.array(mod_t_fit), regex_pars = "b")
```
####can also look at posterior predictive checks with bayesplot
#####We can calculate error of prediction at each value of our outcome, instead of just taking the error from the observed and the 'mean' predicted value (what we'd get with just one linear regression)
```{r}
##two methods
#Compare the overall fit
###we want to compare the probability of y|parameters and the expected values of future errors.. we use cross val. Information criteria gets at cross validation w/o the computational heftiness of cross val. Leave one out (loo package) leaves out 1 observation
```
#Evaluate a 'bayesian posterior p-value'
```{r}
##sy:this function gets posterior prediction stats
y<-mod_data$y ##sy: get original data
y_rep<-rstan::extract(mod_t_fit, "y_rep")[[1]] ##sy: get our predictions from the model
ppc_stat(y=y, yrep=y_rep, stat="sd")
ppc_stat(y=y, yrep=y_rep, stat="mean")
```
Compare those results when using a model with
```{r include=FALSE}
mod_normal <- stan_model("stan/lm.stan")
mod_normal_fit <- sampling(mod_normal, data = mod_data)
```
```{r}
summary(mod_normal_fit, pars = c("b", "sigma"))$summary
```
Alternatively, the Double Exponential (Laplace) distribution can be used for the errors.
This is the equivalent to least quantile regression, where the regression line is the median (50% quantile)
```{r}
mod_dbl_exp <- stan_model("stan/lms.stan")
mod_dbl_exp_fit <- sampling(mod_dbl_exp, data = mod_data)
```
```{r}
summary(mod_dbl_exp_fit, par = c("b", "sigma"))$summary
```
## Heteroskedasticity
In applied regression, heteroskedasticity consistent (HC) or robust standard errors are often used.
However, there is straighforwardly direct translation of HC standard error to regression model this in a Bayesian setting. The sandwich method of estimating HC errors uses the same point estimates for the regression coefficients as OLS, but estimates the standard errors of those coefficients in a second stage from the OLS residuals.
Disregarding differences in frequentist vs. Bayesian inference, it is clear that a direct translation of that method could not be fully Bayesian since the coefficients and errors are not estimated jointly.
In a linear normal regression model with heteroskedasticity, each observation has its own scale parameter, $\sigma_i$,
$$
\begin{aligned}[t]
y_i &\sim \dnorm(X \beta, \sigma_i) .
\end{aligned}
$$
It should be clear that without proper priors this model is not identified, meaning that the posterior distribution is improper.
To estimate this model we have to apply some model to the scale terms, $\sigma_i$.
In fact, you can think of homoskedasticity as the simplest such model; assuming that all $\sigma_i = \sigma$.
A more general model of $\sigma_i$ should encode any information the analyst has about the scale terms.
This can be a distribution or functions of covariates for how we think observations may have different values.
### Covariates
A simple model of heteroskedasticity is if the observations can be split into groups. Suppose the observations are partitioned into $k = 1, \dots, K$ groups, and $k[i]$ is the group of observation $i$,
$$
\sigma_i = \sigma_{k[i]}
$$
Another choice would be to model the scale term with a regression model, for example,
$$
\log(\sigma_i) \sim \dnorm(X \gamma, \tau)
$$
### Student-t
It turns out that the Student-t distribution of error terms from the [Robust Regression] chapter can also be derived as a model of heteroskedasticity.
A reparameterization that will be used quite often is to rewrite a normal distributions with unequal
scale parameters as a continous mixture of a common global scale parameter ($\sigma$), and observation specific local scale parameters, $\lambda_i$,[^globalmixture]
$$
y_i \sim \dnorm(X\beta, \lambda_i \sigma) .
$$
If the local scale paramters are distributed as,
$$
\lamba^2 \sim \dinvgamma(\nu / 2, \nu / 2)
$$
then the above is equivalent to a regression with errors distributed Student-t errors with $\nu$ degrees of freedom,
$$
y_i \sim \dt{\nu}(X \beta, \sigma) .
$$
[^globalmixture] See [this](http://www.sumsar.net/blog/2013/12/t-as-a-mixture-of-normals/) for a visualization of a Student-t distribution a mixture of Normal distributions, and [this](https://www.johndcook.com/t_normal_mixture.pdf) for a derivation of the Student t distribution as a mixture of normals. This scale mixture of normals representation will also be used with shrinkage priors on the regression coefficients.
**Example:** Simulate Student-t distribution with $\nu$ degrees of freedom as a scale mixture of normals. For *s in 1:S$,
1. Simulate $z_s \sim \dgamma(\nu / 2, \nu / 2)$
2. $x_s = 1 / \sqrt{z_s}2$ is draw from $\dt{\nu}(0, 1)$.
When using R, ensure that you are using the correct parameterization of the gamma distribution. **Left to reader**
## References
### Robust regression
- See @GelmanHill2008a [sec 6.6], @BDA2013 [ch 17]
- @Stan2016a [Sec 8.4] for the Stan example using a Student-t distribution
### Heteroskedasticity
- @BDA201 [Sec. 14.7] for models with unequal variances and correlations.
- @Stan2016a reparameterizes the Student t distribution as a mixture of gamma distributions in Stan.
<file_sep># Sampling
- `rstan`: estimation functions
- `bayesplot` Graphing parameter estimates, MCMC diagnostics, posterior predictive checks
- `loo`: out-of-sample predictive performance estimates
- `shinystan`: interactive visual summaries and analysis of MCMC output
- `rstanarm`: Functions for applied regression models
# Model Fitting
- `stan`: compiles and fits a stan model
- `stanc`: parse model and generate C++ code
- `stan_model`: compile stan model
- Inference methods for Stan models
- `sampling`: MCMC
- `optimizing`: optimization
- `vb`: variational algorithm
- `lookup`: find Stan function associated with an R function
A fitted stan model is a `stanfit` object
- `summary`:
- `plot`: plot default methods
- `get_posterior_mean`
For most plotting using `bayesplot`:
- MCMC visualizations
- posterior distributions: histograms (`mcmc_hist`), densities (`mcmc_dens`), violin (`mcmc_violin`)
- posterior interval estimates: `mcmc_intervals`, `mcmc_areas`
- traceplots of MCMC draws: `mcmc_trace`
- scatterplots:
- `mcmc_scatter`: mcmc scatterplot
- `mcmc_hex`: hexbin plot
- `mcmc_parirs`: pairs plot of parameters
- NUTS diagnostics
- MCMC Acceptance rates: `mcmc_nuts_acceptance`
- HMC divergence: `mcmc_nuts_divergence`:
- HMC stepwise `mcmc_nuts_stepsize`:
- HMC Treedpeth: `mcmc_nuts_treedepth`:
- HMC Engery: `mcmc_nuts_engergy`:
- Compare MCMC estimates to TRUE values used to simulate data: `mcmc_recover_interval`, `mcmc_recover_scatter`
- Posterior Predictive Simulation
- Distributions: `ppc_hist`, `ppc_boxplot`, `ppc_freqpoly`, `ppc_dens`, `ppc_dens_overlay`
- Test Statistics: `ppc_stat`, `ppc_stat_freqpoly`,. Distribution of test statistic `T(yrep)` over simulated dataset, compared to the observed value in `T(y)`
- Intervals: `ppc_intervals`, `ppc_ribbon`. Medians and central interval estimates of yrep.
- Predictive Errors: Plots of predictive errors `y - yrep`.
- PPCs for discrete outcomes: `ppc_bars`, `ppc_rootogram`.
- Scatterplots:
- LOO predictive checks:
- `ppc_loo_pit`: probability integral transformation check. QQ plot comparing LOO PITs to uiform distribution, or standardized PIT values to normal.
- `ppc_loo_intervals`, `ppc_loo_ribbon`: Intervals
- Model Comparison: See `loo` packages
- `loo` to calculate PSIS-LOO
- `waic` to calculate WAIC
- `loo::compare` to compare models with LOO
<file_sep>
# Posterior Inference
## Prerequisites
The **[haven](https://cran.r-project.org/package=haven)** package is used to read Stata `.dta` files.
```r
library("rubbish")
library("haven")
```
### Introduction
The posterior distribution is the probability distribution $\Pr(\theta | y)$.
One we have the posterior distribution, or more often a sample from the posterior distribution, it is relatively easy to perform inference on any function of the posterior.
Common means to summarize the post
- mean: $\E(p(\theta | y)) \approx \frac{1}{S} \sum_{i = 1}^S \theta^{(s)}$
- median: $\median(p(\theta | y)) \approx \median \theta^{(s)}$
- quantiles: 2.5%, 5%, 25%, 50%, 75%, 95%, 97.5%
- credible interval:
- central credible interval: the interval between the p/2% and 1 - p/2% quantiles
- highest posterior density interval: the narrowest interval containing p% of distribution
### Functions of the Posterior Distribution
It is also easy to conduct inference on functions of the posterior distribution.
Suppose $\theta^{(1)}, \dots, \theta^{(S)}$ are a sample from $p(\theta | y)$, the
$f(\theta^{(1)}), \dots, f(\theta^{(S)})$ are a sample from $p(f(\theta) | y)$.
This is not easy for methods like MLE that produce point estimates. Even with MLE
- Even in OLS, non-linear functions coefficients generally require either the Delta method or bootstrapping to calculate confidence intervals.
- @BerryGolderMilton2012a, @Goldera,@BramborClarkGolder2006a discuss calculating confidence intervals
- See @Rainey2016b on "transformation induced bias"
- See @Carpenter2016a on how reparameterization affects point estimates; this is a Stan Case study with working code
### Marginal Effects
#### Exmample: Marginal Effect Plot for X
This example from <NAME>'s [Interactions](http://mattgolder.com/interactions) page constructs a marginal effect plot for $X$, where there is an interaction between $X$ and $Z$.
$$
Y = \beta_0 + \beta_x + \beta_z + \beta_{xz} X Z + \epsilon
$$
```r
alexseev <- read_dta("data/alexseev.dta")
```
The regression that is run
```r
mod_f <- xenovote ~ slavicshare * changenonslav + inc9903 + eduhi02 + unemp02 + apt9200 + vsall03 + brdcont
lm(mod_f, data = alexseev)
#>
#> Call:
#> lm(formula = mod_f, data = alexseev)
#>
#> Coefficients:
#> (Intercept) slavicshare
#> 8.942878 0.031486
#> changenonslav inc9903
#> -0.851108 0.000234
#> eduhi02 unemp02
#> -0.039512 1.432013
#> apt9200 vsall03
#> 0.030125 0.661163
#> brdcont slavicshare:changenonslav
#> 2.103688 0.008226
```
Use the `lm_preprocess` function in the [rubbish](https://jrnold.github.com/rubbish) package to turn the model formula into a list with relevant data.
```r
mod_data <- lm_preprocess(mod_f, data = alexseev)[c("X", "y")]
mod_data <- within(mod_data, {
n <- nrow(X)
k <- ncol(X)
# indices of relevant coefficients
M <- 100
changenonslav <- seq(min(X[ , "changenonslav"]), max(X[ , "changenonslav"]),
length.out = M)
idx_b_slavicshare <- which(colnames(X) == "slavicshare")
idx_b_slavicshare_changenonslav <-
which(colnames(X) == "slavicshare:changenonslav")
b_loc <- 0
# data appropriate prior
b_scale <- max(apply(X, 2, sd)) * 3
sigma_scale <- sd(y)
})
```
Get the mean of dydx
```r
dydx <- get_posterior_mean(mod_fit, pars = "dydx")
ggplot(tibble(changenonslav = mod_data$changenonslav,
dydx = dydx[ , "mean-all chains"]),
aes(x = changenonslav, y = dydx)) +
geom_line() +
ylab("Marginal effect of slavic share") +
xlab(paste(expression(Delta, "non-Slavic Share")))
```
<img src="posterior-inference_files/figure-html/unnamed-chunk-8-1.png" width="70%" style="display: block; margin: auto;" />
Plotting each iteration as a line:
```r
dydx_all <-
rstan::extract(mod_fit, pars = "dydx")$dydx %>%
as.tibble() %>%
mutate(.iter = row_number()) %>%
# keep only a few iter
gather(param, value, -.iter) %>%
left_join(tibble(param = paste0("V", seq_along(mod_data$changenonslav)), changenonslav = mod_data$changenonslav),
by = "param")
dydx_all %>%
filter(.iter %in% sample(unique(.iter), 2 ^ 8)) %>%
ggplot(aes(x = changenonslav, y = value, group = .iter)) +
geom_line(alpha = 0.3) +
ylab("Marginal effect of slavic share") +
xlab(paste(expression(Delta, "non-Slavic Share")))
```
<img src="posterior-inference_files/figure-html/unnamed-chunk-9-1.png" width="70%" style="display: block; margin: auto;" />
Summarize the marginal effects with mean, 50% central credible interval, and 90% central credible intervals:
```r
dydx_all %>%
group_by(changenonslav) %>%
summarise(mean = mean(value),
q5 = quantile(value, 0.05),
q25 = quantile(value, 0.25),
q75 = quantile(value, 0.75),
q95 = quantile(value, 0.95)) %>%
ggplot(aes(x = changenonslav,
y = mean)) +
geom_ribbon(aes(ymin = q5, ymax = q95),
alpha = 0.2) +
geom_ribbon(aes(ymin = q25, ymax = q75),
alpha = 0.2) +
geom_line(colour = "blue") +
ylab("Marginal effect of slavic share") +
xlab(expression(paste(Delta, "non-Slavic Share")))
```
<img src="posterior-inference_files/figure-html/unnamed-chunk-10-1.png" width="70%" style="display: block; margin: auto;" />
<file_sep>suppressPackageStartupMessages({
library("knitr")
library("rstan")
library("tidyverse")
library("rubbish")
})
set.seed(92508117 )
options(digits = 3)
knitr::opts_chunk$set(
comment = "#>",
collapse = TRUE,
cache = TRUE,
out.width = "70%",
fig.align = 'center',
fig.width = 6,
fig.asp = 0.618, # 1 / phi
fig.show = "hold"
)
options(dplyr.print_min = 6,
dplyr.print_max = 6)
# Helpful Documentation functions
rpkg_url <- function(pkg) {
paste0("https://cran.r-project.org/package=", pkg)
}
rpkg <- function(pkg) {
paste0("**[", pkg, "](", rpkg_url(pkg), ")**")
}
rdoc_url <- function(pkg, fun) {
paste0("https://www.rdocumentation.org/packages/", pkg, "/topics/", fun)
}
rdoc <- function(pkg, fun, full_name = FALSE) {
text <- if (full_name) paste0(pkg, "::", fun) else pkg
paste0("[", text, "](", rdoc_url(pkg, fun), ")")
}
STAN_VERSION <- "2.14.0"
STAN_URL <- "http://mc-stan.org/documentation/"
STAN_MAN_URL <- paste0("https://github.com/stan-dev/stan/releases/download/v", STAN_VERSION, "/stan-reference-", STAN_VERSION, ".pdf")
standoc <- function(x = NULL) {
if (!is.null(x)) {
STAN_MAN_URL
} else {
paste("[", x, "](", STAN_MAN_URL, ")")
}
}
preprocess_lm <- function(formula, data = NULL, weights = NULL,
contrasts = NULL, na.action = options("na.action"),
offset = NULL, ...) {
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "subset", "weights", "na.action",
"offset"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
mf[[1L]] <- quote(stats::model.frame)
mf <- eval(mf, parent.frame())
mt <- attr(mf, "terms")
mt <- attr(mf, "terms")
out <- list(
y = model.response(mf),
w = as.vector(model.weights(mf)),
offset = as.vector(model.offset(mf)),
X = model.matrix(mt, mf, contrasts),
terms = mt,
xlevels = stats::.getXlevels(mt, mf)
)
out$n <- nrow(out$X)
out$k <- ncol(out$X)
out
}
# placeholder for maybe linking directly to docs
stanfunc <- function(x) {
paste0("`", x, "`")
}
<file_sep># MCMC Diagnostics
There are two parts of checking a Bayesian model:
1. diagnostics: Is the sampler working? Is it adequately approximating the specified posterior distribution: $p(\theta | D)$.
2. model fit: Does the model adequately represent the data?
## Convergence Diagnostics
Under certain conditions, MCMC algorithms will draw a sample from the target posterior distribution after it has converged to equilbrium.
However, since in practice, any sample is finite, there is no guarantee about whether its converged, or is close enough to the posterior distribution.
In general there is no way to prove that the sampler has converged [^converge].
However, there are several statistics that indicate that a sampler has not converged.
[^converge]: This is also the case in optimization with non-convex objective functions.
### Potential Scale Reduction ($\hat{R}$)
In equilibrium, the distribution of samples from chains should be the same regardless of the initial starting
values of the chains [@Stan2016a, Sec 28.2].
One way to check this is to compare the distributions of multiple chains---in equilibrium they should all have the same mean.
Additionally, the split $\hat{R}$ tests for convergence by splitting the chain in half, and testing the hypothesis that the means are the same in each half. This tests for non-stationarity within a chain.
See @Stan2016a [Sec 28.2] for the equations to calculate these.
**TODO:** Examples of passing and non-passing Rhat chains using fake data generated from known functions with a given autocorrelation.
**Rule of Thumb:** The rule of thumb is that R-hat values for all less than 1.1 [source](https://cran.r-project.org/web/packages/rstanarm/vignettes/rstanarm.html).
Note that **all** parameters must show convergence.
This is a necessary but not sufficient condition for convergence.
## Autocorrelation, Effective Sample Size, and MCSE
MCMC samples are dependent. This does not effect the validity of inference on the posterior if the samplers has time to explore the posterior distribution, but it does affect the efficiency of the sampler.
In other words, highly correlated MCMC samplers requires more samples to produce the same level of Monte Carlo error for an estimate.
### Autocorrelation
The effective sample size (ESS) measures the amount by which autocorrelation in samples increases uncertainty (standard errors) relative to an independent sample.
Suppose that the $\rho^2_t$ is the ACF function of a sample of size $N$, the effective sample size, $N_eff$, is
$$
N_{eff} = \frac{N}{\sum_{t = -\infty}^\infty \rho_t} = \frac{N}{1 + 2 \sum_{t = -\infty}^\infty \rho_t}.
$$
**TODO** show that if $\rho_t = 1$ for all $t$ then $N_eff = 1$, and if $\rho_t = 0$ for all $t$ then $N_eff = N$.
See also @Stan2016a [Sec 28.4], @Geyer2011a, and @GelmanCarlinSternEtAl2013a.
**Thinning** Since the autocorrelation tends to decrease as the lag increases, thinning samples will reduce the final autocorrelation in the sample while also reducing the total number of samples saved.
Due to the autocorrelation, the reduction in the number of effective samples will often be less than number of samples removed in thinning.
Both of these will produce 1,000 samples from the poserior, but effective sample size of $B$ will be greater than the effective sample size of $A$, since after thinnin g the autocorrelation in $B$ will be lower.
- *A* Generating 1,000 samples after convergence and save all of them
- *B* Generating 10,000 samples after convergence and save every 10th sample
In this case, A produces 10,000 samples, and B produces 1,000.
The effective sample size of A will be higher than B.
However, due to autocorrelation, the proportional reduction in the effective sample size in B will be less than the thinning: $N_{eff}(A) / N_{eff}(B) < 10$.
- *A* Generating 10,000 samples after convergence and save all of them
- *B* Generating 10,000 samples after convergence and save every 10th sample
Thinning trades off sample size for memory, and due to autocorrelation in samples, loss in effective sample size is less than the loss in sample size.
**Example:** Comparison of the effective sample sizes for data generated with various levels of autocorrelation.
The package `rstan` does not directly expose the function it uses to calculate ESS, so this `ess` function does so (for a single chain).
```{r}
ess <- function(x) {
N <- length(x)
V <- map_dbl(seq_len(N - 1),
function(t) {
mean(diff(x, lag = t) ^ 2, na.rm = TRUE)
})
rho <- head_while(1 - V / var(x), `>`, y = 0)
N / (1 + sum(rho))
}
n <- 1024
ess(rnorm(n))
ess(arima.sim(list(ar = 0.5), n))
ess(arima.sim(list(ar = 0.75), n))
ess(arima.sim(list(ar = 0.875), n))
ess(arima.sim(list(ar = 0.99), n))
```
### Monte Carlo Standard Error (MCSE)
The Monte Carlo standard error is the uncertainty about a statistic in the sample due to sampling error.
With a independent sample of size $N$, the MCSE for the sample mean is
$$
MCSE(\bar{\theta}) = \frac{s}{\sqrt{N}}
$$
where $s$ is the sample standard deviation.
However, MCMC are generally not independent, and the MCSE will be higher than that
of an independent sample. One way to calculate the MCSE with autocorrelated samples
is to use the effective sample size instead of the sample size,
$$
MCSE(\bar{\theta}) = \frac{s}{\sqrt{N_{eff}}}
$$
MCSE for common values: the mean, and any posterior probabilities:
-------------- -----------------------
mean $s_\theta / \sqrt{S}$
probability $\sqrt{p (1 - p) / S}$
-------------- -----------------------
The estimation of standard errors for quantiles, as would be used in is more complicated. See the package `r rpkg("mcmcse")` for Monte Carlo standard errors of quantiles (though calculated in a different method than rstan).
See @BDA3 [Sec. 10.5].
## HMC Specific Diagnostics
HMC produces several diagnostics that indicate that the sampler is breaking and, thus, not sampling from the posterior distribution.
This is unusual, as most Bayesian sampling methods do not give indication of whether they are working well, and all that can be checked are the properties of the samples themselves with methods like $\hat{R}$.
The two diagnostics that HMC provides are
1. divergent transitions
2. maximum treedepth
The HMC sampler has two tuning parameters
1. Stepsize: Length of the steps to take
2. Treedepth: Number of steps to take
Stan chooses intelligent defaults for these values. However, this does not always work, and the divergent transitions and maximum treedepth tuning parameters indicate that these parameters should be adjusted.
### Divergent transitions
**The problem:** The details of the HMC are technical and can be found **TODO**. The gist of the problem is that Stan is using a discrete approximation of a continuous function when integrating.
If the step sizes are too large, the discrete approximation does not work.
Helpfully, when the approximation is poor it does not fail without any indication but will produce "divergent transitions".
*If there are too many divergent transitions, then the sampler is not drawing samples from the entire posterior and inferences will be biased*
**The solution:** Reduce the step size. This can be done by increasing the the `adapt_delta` parameter.
This is the target average proposal acceptance probability in the adaptation, which is used to determine the step size during warmup.
A higher desired acceptance probability (closer to 1) reduces the the step size. A smaller step size means that it will require more steps to explore the posterior distribution.
See @Stan2016a [p. 380]
### Maximum Treedepth
**The problem:** NUTS is an intelligent method to select the number of steps to take in each iteration. However, there is still a maximum number of steps that NUTS will try.
If the sampler is often hitting the maximum number of steps, it means that the optimal number of steps to take in each iteration is higher than the maximum.
While divergent transitions bias inference, a too-small maximum treedepth only affects efficiency.
The sampler is still exploring the posterior distribution, but the exploration will be slower and the autocorrelation higher (effective sample size lower) than if the maximum treedepth were set higher.
**The solution:** Increase the maximum treedepth.
## References
see
- @BDA3 [ p. 267]
- Stan2016a [Ch 28.] for how Stan calculates Rhat, autocorrelations, and ESS.
- See @FlegalHaranJones2008a and the `r rpkg("mcmcse")` for methods to calculate MCMC standard errors and an argument for using ESS as a stopping rule for Bayesian inference.
- [Talk by Geyer on MCSE ](http://www.stat.umn.edu/geyer/mcmc/talk/mcmc.pdf)
<file_sep># Posterior Inference
## Prerequisites
The `r rpkg("haven")` package is used to read Stata `.dta` files.
```{r}
library(devtools)
#install_github("jrnold/rubbish")
library("rubbish") ##sy: jrnold's package, has a script that pre-processes data in the same way as lm (eg, makes the model matrix)
library("haven")
library(data.table)
library(rstan)
library(bayesplot)
```
### Introduction
The posterior distribution is the probability distribution $\Pr(\theta | y)$.
One we have the posterior distribution, or more often a sample from the posterior distribution, it is relatively easy to perform inference on any function of the posterior.
Common means to summarize the post
- mean: $\E(p(\theta | y)) \approx \frac{1}{S} \sum_{i = 1}^S \theta^{(s)}$
- median: $\median(p(\theta | y)) \approx \median \theta^{(s)}$
- quantiles: 2.5%, 5%, 25%, 50%, 75%, 95%, 97.5%
- credible interval:
- central credible interval: the interval between the p/2% and 1 - p/2% quantiles
- highest posterior density interval: the narrowest interval containing p% of distribution
### Functions of the Posterior Distribution
It is also easy to conduct inference on functions of the posterior distribution.
Suppose $\theta^{(1)}, \dots, \theta^{(S)}$ are a sample from $p(\theta | y)$, the
$f(\theta^{(1)}), \dots, f(\theta^{(S)})$ are a sample from $p(f(\theta) | y)$.
This is not easy for methods like MLE that produce point estimates. Even with MLE
- Even in OLS, non-linear functions coefficients generally require either the Delta method or bootstrapping to calculate confidence intervals.
- @BerryGolderMilton2012a, @Goldera,@BramborClarkGolder2006a discuss calculating confidence intervals
- See @Rainey2016b on "transformation induced bias"
- See @Carpenter2016a on how reparameterization affects point estimates; this is a Stan Case study with working code
### Marginal Effects
#### Exmample: Marginal Effect Plot for X
This example from <NAME>'s [Interactions](http://mattgolder.com/interactions) page constructs a marginal effect plot for $X$, where there is an interaction between $X$ and $Z$.
$$
Y = \beta_0 + \beta_x + \beta_z + \beta_{xz} X Z + \epsilon
$$
```{r}
alexseev <- read_dta("data/alexseev.dta")
#alexseev<-as.data.table(alexseev)
```
The regression that is run
```{r}
mod_f <- xenovote ~ slavicshare * changenonslav + inc9903 + eduhi02 + unemp02 + apt9200 + vsall03 + brdcont
lm(mod_f, data = alexseev)
```
Use the `lm_preprocess` function in the [rubbish](https://jrnold.github.com/rubbish) package to turn the model formula into a list with relevant data.
```{r}
mod_data <- lm_preprocess(mod_f, data = alexseev)[c("X", "y")] ##sy: this function from jrnold's 'rubbish' package, and it makes the appropriate model matrix
mod_data <- within(mod_data, {
n <- nrow(X)
k <- ncol(X)
# indices of relevant coefficients
M <- 100
changenonslav <- seq(min(X[ , "changenonslav"]), max(X[ , "changenonslav"]),
length.out = M)
idx_b_slavicshare <- which(colnames(X) == "slavicshare")
idx_b_slavicshare_changenonslav <-
which(colnames(X) == "slavicshare:changenonslav")
b_loc <- 0
# data appropriate prior
b_scale <- max(apply(X, 2, sd)) * 3 ##sy: standardize the data
sigma_scale <- sd(y)
})
```
```{r include = FALSE}
mod <- stan_model("stan/ex-alexseev.stan")
```
```{r include=FALSE}
mod_fit <- sampling(mod, data = mod_data) ##sy: sampling from rstan
```
Get the mean of dydx-this is the
```{r}
dydx <- get_posterior_mean(mod_fit, pars = "dydx")
ggplot(tibble(changenonslav = mod_data$changenonslav,
dydx = dydx[ , "mean-all chains"]),
aes(x = changenonslav, y = dydx)) +
geom_line() +
ylab("Marginal effect of slavic share") +
xlab(paste(expression(Delta, "non-Slavic Share")))
```
Plotting each iteration as a line:
```{r}
dydx_all <-
rstan::extract(mod_fit, pars = "dydx")$dydx %>%
as.tibble() %>%
mutate(.iter = row_number()) %>%
# keep only a few iter
gather(param, value, -.iter) %>%
left_join(tibble(param = paste0("V", seq_along(mod_data$changenonslav)), changenonslav = mod_data$changenonslav),
by = "param")
dydx_all %>%
filter(.iter %in% sample(unique(.iter), 2 ^ 8)) %>%
ggplot(aes(x = changenonslav, y = value, group = .iter)) +
geom_line(alpha = 0.3) +
ylab("Marginal effect of slavic share") +
xlab(paste(expression(Delta, "non-Slavic Share")))
```
Summarize the marginal effects with mean, 50% central credible interval, and 90% central credible intervals:
```{r}
dydx_all %>%
group_by(changenonslav) %>%
summarise(mean = mean(value),
q5 = quantile(value, 0.05),
q25 = quantile(value, 0.25),
q75 = quantile(value, 0.75),
q95 = quantile(value, 0.95)) %>%
ggplot(aes(x = changenonslav,
y = mean)) +
geom_ribbon(aes(ymin = q5, ymax = q95),
alpha = 0.2) +
geom_ribbon(aes(ymin = q25, ymax = q75),
alpha = 0.2) +
geom_line(colour = "blue") +
ylab("Marginal effect of slavic share") +
xlab(expression(paste(Delta, "non-Slavic Share")))
```
<file_sep># Generalized Linear Models
## Generalized Linear Models
Generalized linear models (GLMs) are a class of commonly used models in social science.[^glm-r]
A GLM consists of three components
In GLMs the mean is specified as a function as a function of a linear model of predictors (e.g. $\mat{X} \beta)$),
$$
E(Y) = \mu = g^{-1}(\mat{X} \vec{\beta})
$$
1. A **probability distribution** (**family**) for the outcome. This is usually in the exponential family: common examples include: normal, Binomial, Poisson, Categorical, Multinomial, Poison.
2. A **linear predictor**: $\eta = \mat{X} \beta$
3. A **link function** $g$, such that $\E(Y)= \mu = g^{-1}(\eta)$.
- The link function ($g$) and its inverse ($g^{-1}) translate $\eta$ from $(\-infty, +\infty)$ to the proper range for the probability distribution and back again.
These models are often estimated with MLE, as with the function `r rdoc("stats", "glm")`.
However, these are also easily estimated in a Bayesian setting:
See the help for `r rdoc("stats", "family")` for common probaiblity distributions, `r rdoc("stats", "make.link")` for common links, and the [Wikipedia](https://en.wikipedia.org/wiki/Generalized_linear_model) page for a table of common GLMs.
See the function `r rpkg("VGAM")` for even more examples of link functions and probability distributions.
The **link function**, $g$, maps the mean or parameter to the linear predictor,
$$
g(\mu) = \eta
$$
and the **inverse link function** maps the linear predictor to the mean,
$$
\mu = g^{-1}(\eta)
$$
## Binomial
- The outcomes $Y$ are non-negative integers: $0, 1, 2, \dots, n_i$.
- The total number, $n_i$, can vary by observation.
- Special case: $n_i = 1$ for all $i \in (1, 0)$: logit, probit models.
The outcome is distributed Binomial:
$$
\begin{aligned}[t]
y_i \sim \dbinom\left(n_i, \pi \right)
\end{aligned}
$$
The parameter $\pi \in [0, 1]$ is modeled with a link funcction and a linear predictor.
There are several common link functions, but they all have to map $R \to (0, 1)$.[^binomialcdf]
**Logit:** The logistic function,
$$
\pi_i = \logistic(x_i\T \beta) = \frac{1}{1 + \exp(- x_i\T\beta)} .
$$
Stan function `r stanfunc("softmax")`.
- **Probit:** The CDF of the normal distribution.
$$
\pi_i = \Phi(x_i\T \beta)
$$
Stan function `r stanfunc("normal_cdf")`.
- **cauchit**: The CDF of the Cauchy distribution. Stan function `r stanfunc("cauchy_cdf")`.
- **cloglog**: The inverse of the conditional log-log function (cloglog) is
$$
\pi_i = 1 - \exp(-\exp(x_i\T \beta)) .
$$
Stan function `r stanfunc("inv_cloglog")`.
[^binomialcdf]: Since a CDF maps reals to $(0, 1)$, any CDF can be used as a link function.
## Poisson
TODO
## References
Texts:
- @BDA3 [Ch 16]
- @McElreath2016a [Ch 9]
- @King1998a discusses many common GLM models in an MLE context.
|
7a021c51fff6af98b3c7f01377c99c7a1ccdf864
|
[
"Markdown",
"R",
"RMarkdown"
] | 8
|
RMarkdown
|
syadgir/bayesian_notes
|
182e62dcc795f8307a787c5d2969eecfe1a4145f
|
c405957755c181e843a4e324b2bbe0e32a670d1e
|
refs/heads/master
|
<repo_name>shihchieh822/todo_list<file_sep>/todo/update.php
<?php
header('Content-Type: application/json; charset=utf-8');
include ('../../db.php');
try {
$pdo = new PDO("mysql:host=$db[host];dbname=$db[dbname];port=$db[port];charset=$db[charset]", $db['username'], $db['password']); //pdo的連接方式
} catch (PDOException $e) {
echo "Database connection failed.";
exit;
}
//insert 插入前端所輸入的資料
$sql = 'UPDATE todos SET content = :content WHERE id = :id';
$statement = $pdo ->prepare($sql);
$statement -> bindValue(':content', $_POST['content'], PDO::PARAM_STR );
$statement->bindValue(':id', $_POST['id'], PDO::PARAM_INT);
$result = $statement->execute();//執行$statement
//回傳資料給前端
if (!$result) {
echo 'error';//資料庫回傳資料已json格式 向$pdo索取lastInsertId(最後插入的id)
}
<file_sep>/js/action.js
$(document).ready(function(){
//template
var source = $('#todo-list-item-template').html(); //取出todo-list-item的html 存為source "html()"這種方式可以取出html裡原有的值
var todoTemplate = Handlebars.compile(source); //將source compile過後 存為template
//prepare all todo list items 準備好todo
var todoListUI = ' ';//宣告一個空字串 準備套入todos的li
$.each(todos, function (index, todo) { //這邊拆開todos 變成一個一個的todo
todoListUI = todoListUI + todoTemplate(todo);//來這邊湊成一整個li 然後在塞到下面的語法
});
$('#todo-list').find('li.new').before(todoListUI);//指定在#todo-list的new-li之前插入todoListUI
//create
//enter editor mode
$('#todo-list')
//.on 適用於提醒新增物件也該具備事件功能
.on("dblclick", ".content", function(e){
$(this).prop('contenteditable', true).focus();//直接觸發動作(focus)
})
//create&update
.on('blur', '.content', function(e){
//create&update的blur衝突修正,主要先做判斷式 判斷create&update
var isNew = $(this).closest('li').is('.new');//先找出create與update不一樣的地方 宣告變數
//做判斷式
//create
if (isNew) {
var todo = $(e.currentTarget).text();//先找出li-new的content設定一個blur的事件,再宣告一個擷取內容的變數todo
todo = todo.trim();//清掉content多餘的空白
if (todo.length > 0) {//判斷todo的字串長度是否大於零
var order = $('#todo-list').find('li:not(.new)').length +1;//抓取所以有li之後 再用length+1
$.post("todo/create.php", {content: todo, order:order}, function (data, textStatus, XHR) {
todo = {
id: data.id,
is_complete: false,
content: todo,
}; //content 所宣告的todo為最一開始宣告的,而現在再把todo宣告成另外一個值,覆寫原先todo的值
var li = todoTemplate(todo);
$(e.currentTarget).closest('li').before(li);
},'json');
}
$(e.currentTarget).empty();//清掉li-new的內容
}
//update
else {
//AJAX call
var id = $(this).closest('li').data('id');
var content = $(this).text();
$.post('todo/update.php', {id: id, content: content});
$(this).prop('contenteditable', false);
}
})
//delete
.on('click', '.delete', function(e){
var result = confirm ('do you want to delete?');//confirm是一個彈跳式對話框
if (result) {
//AJAX call
var id = $(this).closest('li').data('id');
$.post('todo/delete.php', {id: id}, function(data, textStatus, xhr){
$(e.currentTarget).closest('li').remove();//這邊的this已經變成function 所以要改使用e.currentTarget
});
}
})
//complete
.on('click', '.checkbox', function(e){
//AJAX call
var id = $(this).closest('li').data('id');
$.post("todo/complete.php", {id: id}, function (data, textStatus, xhr) {
$(e.currentTarget).closest('li').toggleClass('complete'); //toggleClass 一個開關的變數
});
});
$('#todo-list').find('ul').sortable({
items: 'li:not(.new)' ,
stop: function() {
var orderPair = [ ];
$('#todo-list').find('li:not(.new)').each (function(index, li){
orderPair.push({
id: $(li).data('id'),
order: index +1,
});
});
$.post('todo/sort.php', {orderPair: orderPair});
},
});
});
|
fef29f8dd7ca0c3a1d4fcf3ad9c55e5049391d80
|
[
"JavaScript",
"PHP"
] | 2
|
PHP
|
shihchieh822/todo_list
|
080f75c8427fada1812bf753c3241ab4f04d513c
|
90b27647b3c34f6910c1893b1f204162603c3c84
|
refs/heads/main
|
<file_sep>import { AngularFirestoreCollection, AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Injectable } from '@angular/core';
import { Post } from './post';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class PostService {
postsCollection: AngularFirestoreCollection<Post>;
postDoc: AngularFirestoreDocument<Post>;
constructor(private firestore: AngularFirestore) {
this.postsCollection = this.firestore
.collection<Post>('posts', ref => ref.orderBy('published','desc'));
}
getPosts() {
// read the data and metada from firestore with snapshotChanges
return this.postsCollection.snapshotChanges()
.pipe( map(actions => actions.map(res => {
const data = res.payload.doc.data() as Post;
const id = res.payload.doc.id;
return { id, ...data };
})))
}
getPostData(id: string) {
this.postDoc = this.firestore.doc<Post>(`posts/${id}`);
return this.postDoc.valueChanges();
}
}
<file_sep>export interface Post {
title: string;
content: string;
published: Date;
img: string
}<file_sep># Frontend Practices
## My projects while learning front-end development
<file_sep> ## Simple Angular Todo App<file_sep>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, AbstractControl } from '@angular/forms';
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.scss']
})
export class ContactComponent implements OnInit {
// this root form group defines our form model
public blogForm: FormGroup;
constructor( private fb: FormBuilder) { }
ngOnInit(): void {
// initializing form model
this.blogForm = this.fb.group({
name: ['', [Validators.required, this.notIncludeNumber]],
email: ['', [Validators.required, Validators.email]],
message: ['', [Validators.required]]
})
}
notIncludeNumber(c: AbstractControl): { [key: string]: boolean } | null {
let regex = /^[A-Za-z]+$/;
if( !regex.test(c.value) && c.dirty ) {
return {'letters': true }; //invalid
}
return null; //valid
}
submitForm() {
alert(`Hi ${this.blogForm.get('name').value}! Your message ( ${this.blogForm.get('message').value} ) is successfully sent. I will send my reply as soon as possible to your email ( ${this.blogForm.get('email').value} )` );
}
}
<file_sep>## Fetch Api and Async/await Project
### it is a simple http request project with using promise and async/await<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.scss']
})
export class FooterComponent implements OnInit {
year = new Date().getFullYear();
copyright: string = `Copyright ${this.year}. All rights reserved.`;
owner: string = 'Made with ❤ by rido.'
constructor() { }
ngOnInit(): void {
}
}
<file_sep>
# My Angular Blog Project
## An Angular project using Bulma and Firebase
Project url: https://my-ng-blog.web.app/<file_sep># Frontend Mentor - Huddle landing page with single introductory section
## Desktop Design:

## Mobile Design:

|
42dd9e7513100305b27b77f39591c64b2f70d6b5
|
[
"Markdown",
"TypeScript"
] | 9
|
TypeScript
|
ridvanakca/frontend-projects
|
624ca5d91b699d53c21e8778966082950621063e
|
2c62d0c59bfbcb5cacd42d07e50c57d69029c822
|
refs/heads/master
|
<repo_name>VereorNox/EldersUnity<file_sep>/README.md
# EldersUnity
Assorted stuff I'm messing around with before moving onto the Unity engine to make a game
<file_sep>/Colonist.cs
using System;
public class Colonist
{
// TODO can make these private if you want to make getters/setters for em.
public string name, race, profession;
public int health, curse;
public Colonist(string n, string r, string p, int h)
{
name = n;
race = r;
profession = p;
health = h;
// TODO?
curse = 0;
}
public override string ToString()
{
return name+" the "+race+" "+profession+" has "+health+" HP. Their curse is: "+curse;
}
public static Colonist BabyMaker(string name, Colonist parentA, Colonist parentB)
{
string race = "Unknown";
if (parentA.race == parentB.race) {
race = parentA.race;
} else if ((parentA.race == "Human" && parentB.race == "Orc") || (parentA.race == "Orc" && parentB.race == "Human")) {
race = "Half-Orc";
}
// TODO do you want all babies to have the same name? Should the babymaker signature accept a name?
return new Colonist(name, race, "Baby", 100);
}
}<file_sep>/Colony.cs
using System;
using System.Collections.Generic;
class Colony {
private Dictionary<string,Colonist> colonists = new Dictionary<string,Colonist>();
// TODO think about how you will handle duplicate names or namechanges. Using name as a key is powerful but comes with costs.
public Colonist GetColonist(string name) {
Colonist colonist;
if (!colonists.TryGetValue(name, out colonist)) {
// TODO csharp normal exception handling, I haven't looked into this yet.
Console.WriteLine("Couldn't find colonist {name}");
}
return colonist;
}
public void AddColonist(Colonist colonist) {
colonists[colonist.name] = colonist;
return;
}
public int Population() {
return colonists.Count;
}
public void PrintColony() {
foreach (var colonist in colonists) {
Console.WriteLine(colonist.Value);
}
}
//private int happiness;
}<file_sep>/Project.cs
using System;
namespace Main {
class Program {
private static void Main() {
Colony colony = new Colony();
//Ingest our test data from input.txt
string[] colonists = System.IO.File.ReadAllLines(@"input.txt");
foreach (string colonist in colonists) {
string[] fields = colonist.Split(',');
colony.AddColonist(new Colonist(fields[0],fields[1],fields[2],int.Parse(fields[3])));
}
string babyName = "Baby";
colony.AddColonist(Colonist.BabyMaker(babyName,colony.GetColonist("Unga"),colony.GetColonist("Bae")));
Console.WriteLine(colony.Population());
colony.PrintColony();
}
}
}
|
e1d45fccbbb68b68fba6885e9f24a292a44dadb1
|
[
"Markdown",
"C#"
] | 4
|
Markdown
|
VereorNox/EldersUnity
|
02ad994cff0916671b79e7350585cf9a44f76494
|
69e043a01104f06a04ac32d323761ce0139181b2
|
refs/heads/master
|
<file_sep>use crate::config::Config;
use crate::statistics::{CategoryStats, ContinuousValueStats};
use std::sync::Arc;
use std::time::Duration;
use tokio::stream::StreamExt;
mod config;
mod statistics;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
struct RequestResult {
status_code: Result<hyper::StatusCode>,
response_time: f64,
}
struct RequestSummary {
status_code: CategoryStats<String>,
response_time: ContinuousValueStats,
}
fn main() -> Result<()> {
let loaded_config = Config::load("config.toml")?;
let config = Arc::new(loaded_config);
let mut rt = tokio::runtime::Builder::new()
.threaded_scheduler()
.core_threads(config.concurrent_users())
.max_threads(config.concurrent_users())
.enable_all()
.build()?;
rt.block_on(async {
let mut futures = tokio::time::throttle(
Duration::from_secs_f64(1.0 / config.max_requests_per_second()),
tokio::stream::iter(std::iter::repeat(()).take(config.total_users()).map(
|_| {
let full_endpoint = config.target_address().to_owned()
+ config.task_definitions()[0].api_endpoint();
let config_copy = config.clone();
tokio::spawn(async move {
make_request(
&full_endpoint,
config_copy.task_definitions()[0].method(),
)
.await
})
},
)),
);
let mut results: Vec<RequestResult> = vec![];
loop {
let future = futures.next().await;
match future {
Some(result) => {
results.push(result.await.expect("Error").expect("Error"))
}
None => break,
}
}
let summary = RequestSummary {
status_code: CategoryStats::new(
results
.iter()
.map(|result| match &result.status_code {
Ok(code) => format!("{}", code),
Err(err) => format!("{}", err),
})
.collect(),
),
response_time: ContinuousValueStats::new(
results
.iter()
.filter(|result| result.status_code.is_ok())
.map(|result| result.response_time)
.collect::<Vec<f64>>()
.as_ref(),
),
};
println!("status_code: {}", summary.status_code.histogram_as_str());
println!("response_time_mean: {}", summary.response_time.mean());
println!("response_time_median: {}", summary.response_time.median());
println!(
"response_time_90th_percentile: {}",
summary.response_time.percentile_90th()
);
});
Ok(())
}
async fn make_request(endpoint: &str, method: &str) -> Result<RequestResult> {
let endpoint: hyper::Uri = endpoint.parse()?;
let request = hyper::Request::builder()
.uri(endpoint)
.method(method)
.body(hyper::Body::empty())?;
let client = hyper::Client::new();
let now = std::time::SystemTime::now();
let request_result = client.request(request).await;
let elapsed_time = now.elapsed()?.as_secs_f64();
Ok(RequestResult {
status_code: request_result
.map(|response| response.status())
.map_err(|err| err.into()),
response_time: elapsed_time,
})
}
<file_sep>[package]
name = "butterfly-rs"
version = "0.1.0"
authors = ["alanb <<EMAIL>>"]
edition = "2018"
[dependencies]
hyper = "0.13.1"
tokio = { version = "0.2.10", features = ["full"] }
serde = "1.0.104"
serde_derive = "1.0.104"
toml = "0.5.6"
<file_sep>use std::cmp::Ordering;
use std::collections::HashMap;
pub struct ContinuousValueStats {
mean: f64,
median: f64,
percentile_90th: f64,
}
impl Default for ContinuousValueStats {
fn default() -> Self {
Self {
mean: 0f64,
median: 0f64,
percentile_90th: 0f64,
}
}
}
impl ContinuousValueStats {
pub fn new(elements: &[f64]) -> Self {
let mut sorted_elements = elements.to_owned();
sorted_elements.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Less));
Self {
mean: sorted_elements.iter().sum::<f64>() / (sorted_elements.len() as f64),
median: if sorted_elements.len() % 2 == 1 {
sorted_elements[(sorted_elements.len() - 1) / 2]
} else {
(sorted_elements[sorted_elements.len() / 2]
+ sorted_elements[sorted_elements.len() / 2 - 1])
/ 2.0
},
percentile_90th: sorted_elements
[(sorted_elements.len() as f64 * 0.9).floor() as usize],
}
}
pub fn mean(&self) -> f64 {
self.mean
}
pub fn median(&self) -> f64 {
self.median
}
pub fn percentile_90th(&self) -> f64 {
self.percentile_90th
}
}
pub struct CategoryStats<T: std::cmp::Eq + std::hash::Hash> {
histogram: HashMap<T, i32>,
}
impl<T: std::cmp::Eq + std::hash::Hash> Default for CategoryStats<T> {
fn default() -> Self {
Self {
histogram: HashMap::new(),
}
}
}
impl<T: std::cmp::Eq + std::hash::Hash + std::fmt::Display> CategoryStats<T> {
pub fn new(elements: Vec<T>) -> Self {
let mut histogram = HashMap::new();
for element in elements {
histogram
.entry(element)
.and_modify(|count| *count += 1)
.or_insert(1);
}
CategoryStats { histogram }
}
pub fn histogram_as_str(&self) -> String {
self.histogram
.iter()
.map(|(element, count)| format!("[{}]: {}", element, count))
.collect::<Vec<String>>()
.join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_continuous_value_stats_mean() {
let elements = vec![10.0, 3.0, 1.0, 6.0];
let stats = ContinuousValueStats::new(&elements);
assert_eq!(5f64, stats.mean);
}
#[test]
fn test_continuous_value_stats_median() {
let elements = vec![3.0, 1.0, 6.0];
let stats = ContinuousValueStats::new(&elements);
assert_eq!(3.0, stats.median);
}
#[test]
fn test_continuous_value_stats_median_for_even_number() {
let elements = vec![10.0, 3.0, 1.0, 6.0];
let stats = ContinuousValueStats::new(&elements);
assert_eq!(4.5, stats.median);
}
#[test]
fn test_continuous_value_stats_percentile_90th() {
let elements = (0..5).map(|i| i as f64).rev().collect::<Vec<f64>>();
let stats = ContinuousValueStats::new(&elements);
assert_eq!(4.0, stats.percentile_90th);
}
#[test]
fn test_continuous_value_stats_percentile_90th_boundary_value() {
let elements = (0..100).map(|i| i as f64).collect::<Vec<f64>>();
let stats = ContinuousValueStats::new(&elements);
assert_eq!(90.0, stats.percentile_90th);
}
#[test]
fn test_category_stats_histogram() {
let elements = vec![2, 1, 2];
let stats = CategoryStats::new(elements);
assert_eq!(1, *stats.histogram.get(&1).unwrap());
assert_eq!(2, *stats.histogram.get(&2).unwrap());
assert_eq!(true, stats.histogram.get(&3).is_none())
}
}
<file_sep># rust-template
[](https://codecov.io/gh/alanbondarun/butterfly)
This is a rust repository template.
## What's in here?
- Rust basic (binary) project settings
- Github Actions
- Made with Love 💖
<file_sep>[facts]
total_users = 1000
concurrent_users = 10
max_requests_per_second = 10000
target_address = "http://127.0.0.1:8080"
[[tasks]]
api_endpoint = "/api/task"
method = "GET"
<file_sep>use serde_derive::Deserialize;
#[derive(Deserialize)]
pub struct Config {
facts: Facts,
tasks: Vec<TaskDefinition>,
}
#[derive(Deserialize)]
struct Facts {
total_users: usize,
concurrent_users: usize,
max_requests_per_second: f64,
target_address: String,
}
#[derive(Deserialize)]
pub struct TaskDefinition {
api_endpoint: String,
method: String,
}
impl Config {
pub fn load(file_path: &str) -> crate::Result<Config> {
let content = std::fs::read_to_string(file_path)?;
toml::from_str(&content).map_err(|err| err.into())
}
pub fn total_users(&self) -> usize {
self.facts.total_users
}
pub fn concurrent_users(&self) -> usize {
self.facts.concurrent_users
}
pub fn max_requests_per_second(&self) -> f64 {
self.facts.max_requests_per_second
}
pub fn target_address(&self) -> &str {
&self.facts.target_address
}
pub fn task_definitions(&self) -> &Vec<TaskDefinition> {
&self.tasks
}
}
impl TaskDefinition {
pub fn api_endpoint(&self) -> &str {
&self.api_endpoint
}
pub fn method(&self) -> &str {
&self.method
}
}
|
c4a5bbfe1151630ad93d0ea7ceecf3de6804826a
|
[
"TOML",
"Rust",
"Markdown"
] | 6
|
Rust
|
alanbondarun/butterfly
|
fe5b55241dd3e67bafc2566346785de77c1c2b72
|
e1a18aba4da39d54d3d35e1beb5761aa77ad44a1
|
refs/heads/master
|
<file_sep>class canvas
{
constructor()
{
this.width=600;
this.height=400; this.ctx=document.getElementById('canvas').getContext('2d');
}
init()
{
this.ctx.canvas.width=this.width;
this.ctx.canvas.height=this.height;
}
}
class paddle extends canvas
{
constructor()
{
super();
this.pheight=10;
this.pwidth=100;
this.speed=6;
this.px=this.width/2-this.pwidth/2;
this.py=this.height-this.pheight;
this.direction=0;
}
create()
{
this.ctx.beginPath();
this.ctx.fillStyle="#666666"; this.ctx.fillRect(this.px,this.py,this.pwidth,this.pheight)
this.ctx.fill()
}
move()
{
if(this.direction==1)
this.px+=this.speed;
if(this.direction==2)
this.px-=this.speed;
if(this.px<0)
this.px=0
if(this.px+this.pwidth>this.width)
this.px=this.width-this.pwidth
this.create()
}
}
class ball extends paddle
{
constructor()
{
super();
this.radius=10;
this.x=this.width/2;
this.y=this.height-this.radius-this.pheight;
this.color="green";
this.dx=4;
this.dy=3.2;
}
create()
{
this.ctx.beginPath();
this.ctx.arc(this.x,this.y,this.radius,0,Math.PI*2);
this.ctx.fillStyle="red"
this.ctx.fill()
}
move()
{
this.x+=this.dx;
this.y-=this.dy;
if(this.x+this.radius>this.width)
this.dx=-this.dx;
if(this.x-this.radius<0)
this.dx=-this.dx;
if(this.y-this.radius<0)
this.dy=-this.dy;
if((this.y+this.radius)>this.height-this.pheight)
if(this.x+this.radius>p.px&&this.x-this.radius<(p.px+p.pwidth))
this.dy=-this.dy;
else
{
alert("Game Over")
location.reload()
}
this.create();
}
}
var c=new canvas;
var b=new ball;
var p=new paddle
var score=document.getElementById('score'),s=0
c.init()
function fun()
{
c.ctx.clearRect(0,0,c.width,c.height)
p.move()
b.move()
s+=2;
score.innerHTML="Score="+s/100;
requestAnimationFrame(fun)
}
document.addEventListener('click',fun)
//requestAnimationFrame(fun)
window.addEventListener('keydown',function(e)
{
if(e.keyCode==37)
p.direction=2;
if(e.keyCode==39)
p.direction=1
})
window.addEventListener('keyup',function(e)
{
p.direction=0
})<file_sep>Steps to play Game-
1. Open index.html File with any Browser
2. Click on screen
3. to move Paddle Left press Left key,For Right press Right key
4. Now try to highest Score....
|
c6cb88a15de783d5fedbf24ab1435dddf9a6e53f
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
dalchandra/Javascript-canvas
|
47b9307b9e2ffd1e7585f3264bae3fc875a0875a
|
4472b0c528a11c5837d42aed6d1eeebd166f3b59
|
refs/heads/main
|
<repo_name>candracodes/code-quiz<file_sep>/assets/js/script.js
// DEFINE HTML ID ELEMENTS AS VARIABLES
var highScoreLinkEl = document.getElementById("high-score-link");
var timerEl = document.getElementById("timer");
var questionMainContainerEl = document.getElementById("question-main-container");
var questionContainerEl = document.getElementById("question-container");
var startQuizButtonEl = document.getElementById("start-quiz");
var questionsEl = document.getElementById("questions");
var answerButtons = document.getElementsByClassName('answer-button');
var responseEl = document.getElementById("response");
var scoreContainerEl = document.getElementById("score-container");
var playerInfoEl = document.getElementById("player-info");
var resultsContainerEl = document.getElementById("results-container");
var resultsEl = document.getElementById("results");
var questionTextEl = document.getElementById('question-text');
var mainHeaderEl = document.getElementById("main-header");
var submitPlayerEl = document.getElementById("submit-player");
var playerNameEl = document.getElementById("player-name");
var restartQuizButtonEl = document.getElementById("restart-quiz")
var clearQuizButtonEl = document.getElementById("clear-quiz")
var instructionTextEl = document.getElementById("instruction-text");
var noScoresToShow = document.getElementById("no-scores-to-show");
// CREATE TIME AND SCORE RELATED VARIABLES
let timer = 0;
let currentQuestion = 0
let score = 0;
let scoreArray = [];
let timerInterval = false;
// CREATE AN ARRAY THAT CONTAINS QUESTIONS, MULTIPLE CHOICE ANSWERS & CORRECT ANSWERS
let questions = [{
theQuestion: "1. What is JavaScript?",
answers: ["A font that's inspired by coffee.", "A client-side and server-side scripting language inserted into HTML pages and is understood by web browsers.", "An ancient language spoken by Mayans.", "A prescription for a common skin rash."],
answer: "A client-side and server-side scripting language inserted into HTML pages and is understood by web browsers."
},
{
theQuestion: "2. What is an example of JavaScript Data Types?",
answers: ["String", "Number", "Boolean", "All of the above"],
answer: "All of the above"
},
{
theQuestion: "3. What does `var` commonly stand for?",
answers: ["Variable", "Variety", "Varied Associative References", "Very Awkward Response"],
answer: "Variable"
},
{
theQuestion: "4. Which symbols are used for comments in Javascript?",
answers: ["//", "**", "<!--", "!!"],
answer: "//"
},
{
theQuestion: "5. What are all the looping structures in JavaScript?",
answers: ["for", "while", "Both for and while", "!important"],
answer: "Both for and while"
}
]; // end: questions array
// CREATE FUNCTION THAT FIRES OFF A COUNTDOWN
function countdown() {
console.log("The countdown has begun.");
// Countdown Timer
timerInterval = setInterval(function () {
timer--;
timerEl.textContent = timer;
// CONDITION: If the timer is 0, OR, you've reached the last question, do the following
if (timer < 1 || currentQuestion === questions.length) {
// Set timer to 0
timerEl.textContent = 0;
// clear out the remaining time
clearInterval(timerInterval);
//hide question container
questionContainerEl.style.display = "none";
//reveal results container
resultsContainerEl.style.display = "block";
// hide the questions text
questionTextEl.style.display = "none";
//hide the main title
mainHeaderEl.style.display = "none";
};
}, 1000)
} // end: countdown()
// CREATE A FUNCTION TO START THE QUIZ
function startQuiz() {
// set the timer for a minute
timer = 60;
timerEl.textContent = timer;
countdown();
// hide main title text
mainHeaderEl.style.display = "none";
// hide start quiz button
startQuizButtonEl.style.display = "none";
// hide instructions
instructionTextEl.style.display = "none";
// reveal questions
showQuestions();
// hide high scores
scoreContainerEl.style.display = "none";
} //end: startQuiz()
// CREATE FUNCTION THAT SHOWS QUESTIONS
function showQuestions() {
// show questions div
questionContainerEl.style.display = 'block';
// style the questions text
questionTextEl.setAttribute('style', 'font-size:24px; font-weight:bold; color:#247BA0;');
// populate questions
questionTextEl.textContent = questions[currentQuestion].theQuestion;
// populate multiple choice answers
answerButtons[0].textContent = questions[currentQuestion].answers[0];
answerButtons[1].textContent = questions[currentQuestion].answers[1];
answerButtons[2].textContent = questions[currentQuestion].answers[2];
answerButtons[3].textContent = questions[currentQuestion].answers[3];
// run a loop that goes through the entire questions array and calls the checkAnswer function
for (i = 0; i < answerButtons.length; i++) {
answerButtons[i].addEventListener('click', checkAnswer);
}
} // end: showQuestions()
// CREATE A FUNCTION THAT EXAMINES WHETHER THE SELECTED ANSWER IS CORRECT
function checkAnswer(event) {
// CONDITION: Selected answer is correct, so a score of "1" gets added to the total score
if (event.target.textContent === questions[currentQuestion].answer) {
responseEl.style.display = 'block';
responseEl.textContent = 'Correct!';
currentQuestion++;
score++;
// hide the response element after 800 milliseconds
setTimeout(function () {
responseEl.style.display = 'none';
}, 800);
// stop question if it's the last game
if (currentQuestion === questions.length) {
stopQuiz();
}
// else go to next question
else {
showQuestions();
}; // end: else
} // end: if
// CONDITION: Selected answer is incorrect, so no point is added
else {
responseEl.style.display = 'block';
responseEl.textContent = 'Wrong!';
currentQuestion++;
// DEDUCT TIME: Remove 5 seconds from timer when the answer is wrong
timer -= 5;
// hide the response element after 800 milliseconds
setTimeout(function () {
responseEl.style.display = 'none';
}, 800);
// stop game if it's the last question
if (currentQuestion === questions.length) {
stopQuiz();
}
// stop game if it's the last question OR if the timer runs out
else if (timer < 1 || currentQuestion === questions.length) {
stopQuiz();
}
// if there's still time remaining, go to the next question
else {
showQuestions();
};
} // end: else
} // end: checkAnswer()
// CREATE A FUNCTION THAT STOPS THE QUIZ
function stopQuiz() {
// hide all unecessary divs
highScoreLinkEl.style.display = "none";
questionContainerEl.style.display = "none";
startQuizButtonEl.style.display = "none";
questionTextEl.style.display = "none";
mainHeaderEl.style.display = "none";
// show the high score link
highScoreLinkEl.style.display = "block";
// if score is less than zero, make score zero rather than a negative number
if (score <= 0) {
score = 0;
}
// otherwise, show the actually sum of the score
else {
score = score;
}
// display the final score
resultsEl.textContent = score;
// set the timer back to zero
timerEl.textContent = 0;
// show high score link
revealResults();
} // end: stopQuiz()
// CREATE FUNCTION THAT REVEALS RESULTS WHEN TIME IS UP OR QUESTIONS ARE COMPLETE
function revealResults(){
// show the results container
resultsContainerEl.style.display = "block";
// when user clicks submit, high score is revealed
submitPlayerEl.addEventListener('click', showHighScores);
} // end: revealResults()
// CREATE A FUNCTION TO SHOW HIGH SCORES DIV AND ADD LI ELEMENTS BASED ON INPUT VALUE + # OF QUESTIONS ANSWERED CORRECTLY
function showHighScores() {
// if user clicks button without entering name, do nothing
if (playerNameEl.value.length === 0) {
return;
} // end: if
// otherwise, if user has entered a name, do this
else {
// hide the main question container
questionMainContainerEl.style.display = "none";
// show the score/leaderboard container
scoreContainerEl.style.display = "block";
// Use this globally created function for creating/concatenating player list items
scoreListLoop();
} //end: else
} // end: showHighScores(event)
// CREATE A FUNCTION WHERE THE LIST LOOP IS CREATED SO IT CAN BE USED GLOBALLY
function scoreListLoop(){
// Declare updateScore variable for later use.
var updateScore;
// Check to see if this is user's first time taking quiz, and if so... set scoreArray to empty array
scoreArray = JSON.parse(localStorage.getItem('score'));
// This if statement is necessary so that it doesn't throw an error of "null" for the next if statement
if (scoreArray === null){
scoreArray = [];
}
// if no one has submitted a name, AND the score array is 0, then there's nothing to show
if (playerNameEl.value === "" && scoreArray.length === 0) {
noScoresToShow.style.display = "block";
return
}
// otherwise, don't worry about the above if statement and continue with the rest of the logic
else {
noScoresToShow.style.display = "none";
}
// Defining how the loop should use the information to come...
updateScore = {
userName: playerNameEl.value.trim(),
userScore: score
};
// Debugging Test:
console.log("scoreArray is" + scoreArray + " at line 305");
// Add this newly entered info
scoreArray.push(updateScore);
localStorage.setItem('score', JSON.stringify(scoreArray));
// DISPLAY: Create list items
for (i = 0; i < scoreArray.length; i++) {
console.log("scoreArray is" + scoreArray + " at line 313");
// TODO: Scenario: User has played the game before, historical data is saved locally, HOWEVER, the else is still creating a list element with an empty string, and a value of 0. Continue to explore solution for this.
if (playerNameEl.value === "" && scoreArray.length === 0) {
noScoresToShow.style.display = "block";
return
}
else {
let score = scoreArray[i].userName + ' : ' + scoreArray[i].userScore;
li = document.createElement('li');
li.textContent = score;
playerInfoEl.appendChild(li);
// Debugging Test:
console.log("scoreArray is" + scoreArray + " at line 324");
} //end: else
} // end: for
}
// *******************************************************
// CREATE COLLECTION OF EVENT LISTENERS
// *******************************************************
// ACTION: FIRE OFF QUIZ WHEN USER CLICKS "Start Quiz"
startQuizButtonEl.addEventListener('click', startQuiz);
// ACTION: Restart quiz by simply reloading the main page
restartQuizButtonEl.addEventListener('click', function() {
location.href = 'index.html';
});
// ACTION: Clear out high scores from local storage
clearQuizButtonEl.addEventListener('click', function() {
console.log("Score have been cleared");
localStorage.clear();
playerInfoEl.innerHTML = '';
});
// ACTION: See high scores/ Leaderboard
highScoreLinkEl.addEventListener('click', function() {
// Fire off the function that creates player name and player score list items
scoreListLoop();
// Show score container
scoreContainerEl.style.display = "block";
// Show player info
playerInfoEl.style.display = "block";
// Hide questions container
questionMainContainerEl.style.display = "none";
});
<file_sep>/README.md
# Code Quiz
A timed quiz on JavaScript fundamentals that stores high scores.
## Important URLs
* [Deployed Application URL](https://candracodes.github.io/code-quiz/)
* [GitHub Repo URL](https://github.com/candracodes/code-quiz)
## Foreword
* This application aims to accomplish the following:
* Adhere to the [Assignment Guidelines](./assets/_guide/README.md) to ensure submission is in compliance with acceptance criteria
* Investigate apt Javascript related questions in order to populate accurate questions and answers
## User Story
```
AS A coding boot camp student
I WANT to take a timed quiz on JavaScript fundamentals that stores high scores
SO THAT I can gauge my progress compared to my peers
```
## Acceptance Criteria
```
GIVEN I am taking a code quiz
WHEN I click the start button
THEN a timer starts and I am presented with a question
WHEN I answer a question
THEN I am presented with another question
WHEN I answer a question incorrectly
THEN time is subtracted from the clock
WHEN all questions are answered or the timer reaches 0
THEN the game is over
WHEN the game is over
THEN I can save my initials and my score
```
## Mock-Up
* This project should behave like this screenshot:

* Here are actual screenshots from the deployed application:


## Licensing
The project is made possible with the following Licensing:
- [MIT](license.txt)
## Contact Developer
For additional information, contact this application's developer: <EMAIL>
|
0a50eb22ba1993a59f630e22208e034ecaa526b8
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
candracodes/code-quiz
|
e087d620c081f0fec605f055317ac7626402a179
|
507a2206d7b6a61e94f5e97550129ea121a68a6b
|
refs/heads/main
|
<repo_name>rpickett0173/papergainz<file_sep>/hello/apps.py
from django.apps import AppConfig
import datetime
class HomeConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'hello'
def ready(self):
print("starting scheduler ...")
print(datetime.datetime.today())
from .Scheduler import updater
updater.start()
<file_sep>/hello/migrations/0006_auto_20210425_1349.py
# Generated by Django 3.2 on 2021-04-25 18:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0005_bets'),
]
operations = [
migrations.RemoveField(
model_name='bets',
name='win',
),
migrations.AddField(
model_name='bets',
name='result',
field=models.BooleanField(null=True),
),
migrations.AddField(
model_name='bets',
name='team1',
field=models.CharField(max_length=300, null=True),
),
migrations.AddField(
model_name='bets',
name='team2',
field=models.CharField(max_length=300, null=True),
),
migrations.AddField(
model_name='bets',
name='team_bet',
field=models.CharField(max_length=300, null=True),
),
migrations.AddField(
model_name='bets',
name='winloss',
field=models.IntegerField(null=True),
),
migrations.AlterField(
model_name='bets',
name='game_ID',
field=models.PositiveIntegerField(null=True),
),
]
<file_sep>/hello/migrations/0009_dotaplayerranking.py
# Generated by Django 3.2 on 2021-04-29 19:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0008_auto_20210429_1212'),
]
operations = [
migrations.CreateModel(
name='DotaPlayerRanking',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=300)),
('rank', models.PositiveIntegerField()),
('avatar', models.TextField(blank=True)),
],
),
]
<file_sep>/gettingstarted/urls.py
from django.urls import path, include
from django.contrib import admin
import hello.views
from hello import views
admin.autodiscover()
# To add a new path, first import the app:
# import blog
#
# Then add the new path:
# path('blog/', blog.urls, name="blog")
#
# Learn more here: https://docs.djangoproject.com/en/2.1/topics/http/urls/
urlpatterns = [
path("admin/", admin.site.urls),
path('', views.home, name='<NAME>'),
path('Home.html', views.home, name='<NAME>'),
path('Login.html', views.login_view, name='Login'),
path('Sign Up.html', views.signUp, name='Sign Up'),
path('My Profile.html', views.myProfile, name='My Profile'),
path('My Bets.html', views.myBets, name='My Bet History'),
path('FAQ.html', views.FAQ, name='Frequently Asked Questions'),
path('eSports.html', views.eSports, name='eSports'),
path('CSGO.html', views.CSGO, name='CS:GO'),
path('League.html', views.League, name='League of Legends'),
path('DOTA.html', views.DOTA, name='DOTA 2'),
path('Player Rankings.html', views.player_rankings, name='Dota Pro Player Rankings'),
path('Sports.html', views.sports, name='Sports'),
path('Baseball.html', views.Baseball, name='MBA'),
path('Basketball.html', views.Basketball, name='NBA'),
path('Hockey.html', views.Hockey, name='NHL'),
path('test_gamepage.html', views.test_gamepage, name='Testing Game Page'),
path('test_mybets.html', views.test_mybets, name='Testing Bet History'),
path('test_signup.html', views.test_signup, name='Testing Signup'),
]
<file_sep>/hello/migrations/0013_rename_time_games_time_data.py
# Generated by Django 3.2 on 2021-04-30 18:39
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('hello', '0012_alter_dotaplayerranking_rank'),
]
operations = [
migrations.RenameField(
model_name='games',
old_name='time',
new_name='time_data',
),
]
<file_sep>/hello/migrations/0017_auto_20210501_1433.py
# Generated by Django 3.2 on 2021-05-01 19:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0016_bets_username'),
]
operations = [
migrations.AddField(
model_name='games',
name='team1_amount',
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name='games',
name='team1_odds',
field=models.DecimalField(decimal_places=2, default=0.5, max_digits=3),
),
migrations.AddField(
model_name='games',
name='team2_amount',
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name='games',
name='team2_odds',
field=models.DecimalField(decimal_places=2, default=0.5, max_digits=3),
),
]
<file_sep>/requirements.txt
django
gunicorn
django-heroku
requests
apscheduler
sportsipy
datetime
<file_sep>/hello/migrations/0020_auto_20210502_1822.py
# Generated by Django 3.2 on 2021-05-02 23:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0019_auto_20210502_1701'),
]
operations = [
migrations.AlterField(
model_name='bets',
name='bet_odds',
field=models.DecimalField(decimal_places=2, default=1.5, max_digits=10),
),
migrations.AlterField(
model_name='games',
name='team1_amount',
field=models.PositiveIntegerField(default=1),
),
migrations.AlterField(
model_name='games',
name='team2_amount',
field=models.PositiveIntegerField(default=1),
),
]
<file_sep>/hello/migrations/0005_bets.py
# Generated by Django 3.2 on 2021-04-22 16:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0004_rewards'),
]
operations = [
migrations.CreateModel(
name='Bets',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_ID', models.PositiveIntegerField()),
('game_ID', models.PositiveIntegerField()),
('date_placed', models.DateTimeField(auto_now=True)),
('bet_amount', models.PositiveIntegerField()),
('win', models.BooleanField()),
],
),
]
<file_sep>/hello/migrations/0015_alter_bets_date_placed.py
# Generated by Django 3.2 on 2021-05-01 00:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0014_alter_games_time_data'),
]
operations = [
migrations.AlterField(
model_name='bets',
name='date_placed',
field=models.DateTimeField(),
),
]
<file_sep>/hello/signUp/views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
#signUp
def signUp(request):
return render(request, 'Sign Up.html')<file_sep>/hello/migrations/0018_alter_users_balance.py
# Generated by Django 3.2 on 2021-05-02 00:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0017_auto_20210501_1433'),
]
operations = [
migrations.AlterField(
model_name='users',
name='balance',
field=models.PositiveIntegerField(default=10000),
),
]
<file_sep>/hello/models.py
from django.db import models
# Create your models here.
class Users(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=100)
balance = models.PositiveIntegerField(default = 10000)
def __str__(self):
return self.username
class Games(models.Model):
name = models.CharField(max_length=300)
match_id = models.PositiveIntegerField(null=True)
sport = models.CharField(max_length=300)
time_data = models.DateTimeField()
team1 = models.CharField(max_length=300)
team1_odds = models.FloatField(default=1.5)
team1_amount = models.PositiveIntegerField(default=1)
team2 = models.CharField(max_length=300)
team2_odds = models.FloatField(default=1.5)
team2_amount = models.PositiveIntegerField(default=1)
winner = models.CharField(max_length=300)
def __str__(self):
return self.name
class Rewards(models.Model):
name = models.CharField(max_length=300)
price = models.PositiveSmallIntegerField()
reward_type = models.CharField(max_length=300)
def __str__(self):
return self.name
# Bets model records each and every bet placed, the associated user and game IDs,
# the date it was placed, details on the game (team1, team2), the team that
# the user bet on, the size of the bet, and the result of their bet (win=1, loss=0)
# and how much they won/loss.
class Bets(models.Model):
user_ID = models.PositiveIntegerField()
game_ID = models.PositiveIntegerField(null=True) # null=true allows for this value to be null in the db
username = models.CharField(max_length=100, null=True)
team1 = models.CharField(max_length=300, null=True)
team2 = models.CharField(max_length=300, null=True)
team_bet = models.CharField(max_length=300,null=True)
date_placed = models.DateTimeField() #auto_now automatically makes this value the current time when the method is called
bet_amount = models.PositiveIntegerField()
bet_odds = models.FloatField(default=1.5)
result = models.BooleanField(null=True)
winloss = models.IntegerField(null=True)
def __str__(self):
return str(self.user_ID)
class DotaPlayerRanking(models.Model):
name = models.CharField(max_length=300)
rank = models.PositiveIntegerField(blank=True, null=True)
steamid = models.TextField(null=True)
avatar = models.TextField(blank=True)
def __str__(self):
return self.name
<file_sep>/hello/migrations/0019_auto_20210502_1701.py
# Generated by Django 3.2 on 2021-05-02 22:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0018_alter_users_balance'),
]
operations = [
migrations.AddField(
model_name='bets',
name='bet_odds',
field=models.DecimalField(decimal_places=2, default=1.5, max_digits=3),
),
migrations.AlterField(
model_name='games',
name='team1_odds',
field=models.DecimalField(decimal_places=2, default=1.5, max_digits=3),
),
migrations.AlterField(
model_name='games',
name='team2_odds',
field=models.DecimalField(decimal_places=2, default=1.5, max_digits=3),
),
]
<file_sep>/hello/migrations/0022_auto_20210502_1846.py
# Generated by Django 3.2 on 2021-05-02 23:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0021_alter_bets_bet_odds'),
]
operations = [
migrations.AlterField(
model_name='games',
name='team1_odds',
field=models.FloatField(default=1.5),
),
migrations.AlterField(
model_name='games',
name='team2_odds',
field=models.FloatField(default=1.5),
),
]
<file_sep>/hello/migrations/0014_alter_games_time_data.py
# Generated by Django 3.2 on 2021-04-30 19:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0013_rename_time_games_time_data'),
]
operations = [
migrations.AlterField(
model_name='games',
name='time_data',
field=models.DateTimeField(),
),
]
<file_sep>/hello/Scheduler/updater.py
from apscheduler.schedulers.background import BackgroundScheduler
from hello.views import GameData_Handler
def start():
print("Started")
scheduler = BackgroundScheduler()
gamedata = GameData_Handler()
# Cron timers
# scheduler.add_job(gamedata.DotaRank,"cron",hour=4,minute=59,second=59, id="game_collector_001", replace_existing=True)
# scheduler.add_job(gamedata.get_api_data,"cron",hour=4,minute=59,second=59, id="API_job", replace_existing=True)
# scheduler.add_job(gamedata.calculate_payout_esport,"cron",hour=4 ,minute=59,second=59, id="Payout_job", replace_existing=True)
# scheduler.add_job(gamedata.calculate_payout_sport,"cron",hour=4,minute=59,second=59, id="Payout_job", replace_existing=True)
# interval timers
# scheduler.add_job(gamedata.DotaRank,"interval", minutes=5, seconds=0, id="game_collector_001", replace_existing=True)
# scheduler.add_job(gamedata.get_api_data,"interval", minutes=5, seconds=0, id="API_job", replace_existing=True)
# scheduler.add_job(gamedata.calculate_payout_esport,"interval", minutes=5, seconds=0, id="eSportPayout_job", replace_existing=True)
# scheduler.add_job(gamedata.calculate_payout_sport,"interval", minutes=5, seconds=0, id="SportPayout_job", replace_existing=True)
# Force timers (UTC)
# scheduler.add_job(gamedata.DotaRank, "cron",hour=0,minute=58,second=0, id="game_collector_001", replace_existing=True)
# scheduler.add_job(gamedata.get_api_data, "cron",hour=0,minute=58,second=0, id="API_job", replace_existing=True)
scheduler.add_job(gamedata.calculate_payout_esport, "cron",hour=2,minute=18,second=0, id="eSportPayout_job", replace_existing=True)
scheduler.add_job(gamedata.calculate_payout_sport, "cron",hour=2,minute=18,second=0, id="SportPayout_job", replace_existing=True)
scheduler.start()
<file_sep>/hello/urls.py
from django.urls import path
from . import views
#home
urlpatterns = [
path('Home.html', views.hello, name='hello'),
path('Sign.html', views.signUp, name='signUp')
]
<file_sep>/hello/migrations/0016_bets_username.py
# Generated by Django 3.2 on 2021-05-01 01:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0015_alter_bets_date_placed'),
]
operations = [
migrations.AddField(
model_name='bets',
name='username',
field=models.CharField(max_length=100, null=True),
),
]
<file_sep>/hello/sportsSchedules.py
from sportsipy.mlb.schedule import Schedule as baseballSchedule
from sportsipy.mlb.teams import Teams as baseballTeams
from sportsipy.fb.schedule import Schedule as soccerSchedule
from sportsipy.fb.team import Team as soccerTeams
from sportsipy.nba.schedule import Schedule as basketballSchedule
from sportsipy.nba.teams import Teams as basketballTeams
from sportsipy.nfl.schedule import Schedule as footballSchedule
from sportsipy.nfl.teams import Teams as footballTeams
from datetime import *
def getBaseballSchedule():
todaysGames = []
today = date.today()
teams = baseballTeams(2021)
for team in teams:
print(team.abbreviation)
teamSchedule = baseballSchedule(team.abbreviation)
for game in teamSchedule:
if game.datetime.date() == today:
todaysGames.append(game)
print("Team added to list")
return todaysGames
def getBasketballSchedule():
todaysGames = []
today = date.today()
teams = basketballTeams(2021)
for team in teams:
print(team.abbreviation)
teamSchedule = basketballSchedule(team.abbreviation)
for game in teamSchedule:
if game.datetime.date() == today:
todaysGames.append(game)
print("Team added to list")
return todaysGames
def getFootballSchedule():
todaysGames = []
today = date.today()
teams = footballTeams(2021)
for team in teams:
print(team.abbreviation)
teamSchedule = footballSchedule(team.abbreviation)
for game in teamSchedule:
if game.datetime.date() == today:
todaysGames.append(game)
print("Team added to list")
return todaysGames
if __name__ == "__main__":
#football_schedule = getFootballSchedule()
#basketball_schedule = getBasketballSchedule()
baseball_schedule = getBaseballSchedule()
<file_sep>/hello/migrations/0003_auto_20210421_1943.py
# Generated by Django 3.2 on 2021-04-22 00:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0002_auto_20210417_2021'),
]
operations = [
migrations.CreateModel(
name='Games',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=300)),
('sport', models.CharField(max_length=300)),
('time', models.DateTimeField(auto_now=True)),
('team1', models.CharField(max_length=300)),
('team2', models.CharField(max_length=300)),
('winner', models.CharField(max_length=300)),
],
),
migrations.AlterField(
model_name='users',
name='password',
field=models.CharField(max_length=100),
),
migrations.AlterField(
model_name='users',
name='username',
field=models.CharField(max_length=100),
),
]
<file_sep>/hello/migrations/0021_alter_bets_bet_odds.py
# Generated by Django 3.2 on 2021-05-02 23:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0020_auto_20210502_1822'),
]
operations = [
migrations.AlterField(
model_name='bets',
name='bet_odds',
field=models.FloatField(default=1.5),
),
]
<file_sep>/hello/migrations/0010_dotaplayerranking_steamid.py
# Generated by Django 3.2 on 2021-04-30 13:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0009_dotaplayerranking'),
]
operations = [
migrations.AddField(
model_name='dotaplayerranking',
name='steamid',
field=models.TextField(null=True),
),
]
<file_sep>/hello/views.py
from django.shortcuts import render
from django.http import HttpResponse
import requests
import os
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from .models import *
from .sportsSchedules import getBaseballSchedule
import datetime
from datetime import timedelta
import json
import requests
from sportsipy.nba.schedule import Schedule as basketballSchedule
from sportsipy.nba.teams import Teams as basketballTeams
from sportsipy.nhl.teams import Teams as hockeyTeams
from sportsipy.nhl.teams import Schedule as hockeySchedule
from sportsipy.mlb.schedule import Schedule as baseballSchedule
from sportsipy.mlb.teams import Teams as baseballTeams
from .forms import BetForm
############################# VIEWS #############################
def home(request):
return render(request, 'Home.html')
def signUp(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('<PASSWORD>')
print(username)
print(raw_password)
temp=Users(username=username, password=<PASSWORD>, balance=10000)
temp.save()
# user = authenticate(username=username, password=<PASSWORD>)
# login(request, user)
return redirect('Home.html')
else:
print("failed")
form = UserCreationForm()
return render(request, 'Sign Up.html', {'form': form})
def login_view(request):
last_login = ""
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
# log in user
user = form.get_user()
last_login = User.objects.get(username=user).last_login # Grab information from auth_user
login(request, user)
request.session.set_expiry(0)
print(user)
# Give user payout
if(last_login != None):
if (last_login.date() < datetime.date.today()):
current_user = Users.objects.get(username=user)
current_user.balance = current_user.balance + 1000
current_user.save()
else:
current_user = Users.objects.get(username=user)
current_user.balance = current_user.balance
current_user.save()
return redirect('Home.html')
else:
form = AuthenticationForm()
return render(request, 'Login.html', {'form': form})
def myProfile(request):
print(request.user.username)
if(request.user.is_authenticated):
current_user = Users.objects.get(username=request.user.username)
print(current_user)
context = {
'current_user' : current_user
}
return render(request, 'My Profile.html' , context)
else:
return render(request, 'My Profile.html')
#displays bet history of user (filtered by ID) after validating user login
def myBets(request):
if request.user.is_authenticated:
betData = Bets.objects.all()
print(request.user.id)
context = {
'betData' : betData
}
return render(request, 'My Bets.html', context)
return render(request, 'My Bets.html')
def FAQ(request):
return render(request, 'FAQ.html')
def placeBet(request):
gameData= Games.objects.all()
form = BetForm(request.POST or None)
print("\n\nDEBUG1111\n\n")
if request.user.is_authenticated:
print("\ndoesnt even get authenticated")
if form.is_valid():
print('is valid')
user_ID = request.user.id
game_ID = form.cleaned_data['game_ID']
date_placed = datetime.datetime.today()
team_bet = form.cleaned_data['team_bet']
bet_amount = form.cleaned_data['bet_amount']
if(team_bet=="force" and bet_amount==1234):
print("\nCALLING FORCE PAYOUT\n")
GameData_Handler.forcePayout(game_ID)
form = BetForm(request.POST or None)
context = {
'form':form,
'gameData' : gameData
}
return context
print('\nNOT FORCING PAYOUT\n')
game = Games.objects.get(match_id=game_ID)
team1=game.team1
team2=game.team2
current_user = Users.objects.get(username=request.user.username)
if (bet_amount <= current_user.balance and game.time_data.strptime(game.time_data.strftime("%Y-%m-%d %H:%M:%S"), '%Y-%m-%d %H:%M:%S') > datetime.datetime.strptime(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), '%Y-%m-%d %H:%M:%S')):
current_user.balance = current_user.balance - bet_amount
current_user.save()
print("\n\nDEBUG333\n\n")
if(team_bet==game.team1):
bet_odds=game.team1_odds
else:
bet_odds=game.team2_odds
temp = Bets(user_ID=user_ID, game_ID=game_ID, date_placed=date_placed, bet_amount=bet_amount, team1=team1, team2=team2, team_bet=team_bet,username= current_user, bet_odds=bet_odds)
temp.save()
odds=GameData_Handler.updateOdds(game_ID, team_bet, bet_amount)
else:
print("invalid")
context = {
'form':form,
'gameData' : gameData
}
return context
def eSports(request):
return render(request, 'eSports.html')
def CSGO(request):
return render(request, 'CSGO.html', placeBet(request))
def League(request):
return render(request, 'League.html', placeBet(request))
def DOTA(request):
return render(request, 'DOTA.html', placeBet(request))
def player_rankings(request):
playerData = DotaPlayerRanking.objects.all()
context = {'playerData' : playerData}
return render(request, 'Player Rankings.html', context)
def sports(request):
return render(request, 'sports.html')
def Basketball(request):
return render(request, 'Basketball.html', placeBet(request))
def Baseball(request):
return render(request, 'Baseball.html', placeBet(request))
def Hockey(request):
return render(request, 'Hockey.html', placeBet(request))
def test_signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1') #'password1' because theres 'password1' and '<PASSWORD>', one for the first box, the second for the password verification
print(username)
print(raw_password)
temp=Users(username=username,password=<PASSWORD>)
temp.save()
return redirect('Home.html')
else:
print("failed")
form = UserCreationForm()
return render(request, 'test_signup.html', {'form': form})
def test_gamepage(request):
gameData= Games.objects.all()
form = BetForm(request.POST or None)
if form.is_valid():
user_ID = 0
game_ID = form.cleaned_data['game_ID']
date_placed = datetime.date.today()
team_bet = form.cleaned_data['team_bet']
bet_amount = form.cleaned_data['bet_amount']
game = Games.objects.get(match_id=game_ID)
team1=game.team1
team2=game.team2
temp = Bets(user_ID=user_ID, game_ID=game_ID, date_placed=date_placed, bet_amount=bet_amount, team1=team1, team2=team2, team_bet=team_bet)
temp.save()
context = {
'form':form,
'gameData' : gameData
}
return render(request, 'test_gamepage.html', context)
def test_mybets(request):
if request.user.is_authenticated:
betData= Bets.objects.filter(id=request.user.id)
else:
print("\n\nNOT LOGGED IN\n\n")
betData="None"
context = {
'betData' : betData
}
return render(request, 'test_mybets.html', context)
############################# OTHER FUNCTIONS #############################
class GameData_Handler():
def updateOdds(matchid, team, amount):
#If this is the first bet on a match, a row element needs to be created
match=Games.objects.get(match_id=matchid)
if(match.team1_amount==0):
match.team1_amount=1
if(match.team2_amount==0):
match.team2_amount=1
if(team==match.team1):
match.team1_amount += amount
else:
match.team2_amount += amount
total = match.team1_amount + match.team2_amount
match.team1_odds = total/match.team1_amount
print("\n")
print(match.team1_odds)
match.team2_odds = total/match.team2_amount
print("\n")
print(match.team2_odds)
match.save()
if(team==match.team1):
return match.team1_odds
else:
return match.team2_odds
def forcePayout(game_ID):
print('\nFORCING PAYOUT\n')
betData = Bets.objects.filter(game_ID=game_ID)
userData = Users.objects.all()
for bet in betData:
if(bet.team_bet == bet.team1):
print("Dealing with a win with username: ")
print(bet.username)
if(bet.result == None):
winloss = (bet.bet_odds*bet.bet_amount) # replace 1 with the decimal odds value
bet.winloss=winloss
bet.result=True
bet.save()
for user in userData:
if(bet.username == user.username):
print("Paying win to ")
print(bet.username)
newbalance = user.balance + winloss
user.balance=newbalance
user.save()
print("Set %s balance to %d" %(user.username, newbalance))
else:
if((bet.result == None) or (bet.team_bet == bet.team2)):
print("Dealing with a loss with username: ")
print(bet.username)
winloss = -bet.bet_amount
bet.winloss=winloss
bet.result=False
bet.save()
# we dont need to update a loser balance because the amount the lose is already deducted when they lose
def calculate_payout_esport(self):
betData = Bets.objects.all()
userData = Users.objects.all()
# LOL
link_lol = 'https://api.pandascore.co/lol/matches/past?token=<KEY>'
r_lol = requests.get(link_lol)
data_lol = json.loads(r_lol.text)
for game in data_lol:
gameID = game['id']
print("Game ID:",gameID)
gameFinished = game['status']
print("Finished:",gameFinished)
if (gameFinished == 'finished'):
winnerData = game['winner']
winner = winnerData['name']
print("winner:",winner)
if(winner == None):
print("No winner")
for bet in betData :
if(bet.game_ID == gameID):
bet.winloss=0
bet.save()
else:
for bet in betData:
if(bet.game_ID == gameID):
if(bet.team_bet == winner):
if(bet.result == None):
print("Correct bet")
winloss = (bet.bet_odds*bet.bet_amount) # replace 1 with the decimal odds value
bet.winloss=winloss
bet.result=True
bet.save()
for user in userData:
print("Username",user.username)
print("bet user",bet.username)
if(bet.username == user.username):
print(user.username)
newbalance = user.balance + winloss
print(newbalance)
user.balance=newbalance
user.save()
else:
if(bet.result == None):
print("wrong bet")
winloss = -bet.bet_amount
bet.winloss=winloss
bet.result=False
bet.save()
# we dont need to update a loser balance because the amount the lose is already deducted when they lose
#CSGO Payout
link_csgo = 'https://api.pandascore.co/csgo/matches/past?token=<KEY>'
r_csgo = requests.get(link_csgo)
data_csgo = json.loads(r_csgo.text)
for game in data_csgo:
print(game)
gameID = game['id']
print("Game ID:", gameID)
gameFinished = game['status']
print("Finished:", gameFinished)
if (gameFinished == 'finished'):
winnerData = game['winner']
print("winnerData:", winnerData)
winner = winnerData['name']
print("winner:", winner)
if (winner == None):
print("No winner")
for bet in betData:
if (bet.game_ID == gameID):
winloss = -bet.bet_amount
bet.winloss=winloss
bet.result=False
bet.save()
else:
for bet in betData:
if (bet.game_ID == gameID):
if (bet.team_bet == winner):
if (bet.result == None):
print("Correct bet")
winloss = (bet.bet_odds * bet.bet_amount)
bet.winloss=winloss
bet.result=True
bet.save()
for user in userData:
print("Username", user.username)
print("bet user", bet.username)
if (bet.username == user.username):
print(user.username)
newbalance = user.balance + winloss
print(newbalance)
user.balance=newbalance
user.save()
else:
if (bet.result == None):
print("wrong bet")
winloss = -bet.bet_amount
bet.winloss=winloss
bet.result=False
bet.save()
# we dont need to update a loser balance because the amount the lose is already deducted when they lose
#DOTA2 Payout
link_dota = 'https://api.pandascore.co/dota2/matches/past?token=<KEY>'
r_dota = requests.get(link_dota)
data_dota = json.loads(r_dota.text)
for game in data_dota:
print(game)
gameID = game['id']
print("Game ID:", gameID)
gameFinished = game['status']
print("Finished:", gameFinished)
if (gameFinished == 'finished'):
winnerData = game['winner']
print("winnerData:", winnerData)
winner = winnerData['name']
print("winner:", winner)
if (winner == None):
print("No winner")
for bet in betData:
if (bet.game_ID == gameID):
bet.winloss=0
bet.save()
else:
for bet in betData:
if (bet.game_ID == gameID):
if (bet.team_bet == winner): #IF WIN
if (bet.result == None):
print("Correct bet")
winloss = (bet.bet_odds * bet.bet_amount)
bet.winloss=winloss
bet.result=True
bet.save()
for user in userData:
print("Username", user.username)
print("bet user", bet.username)
if (bet.username == user.username):
print(user.username)
newbalance = user.balance + winloss
print(newbalance)
user.balance=newbalance
user.save()
else: # IF LOSE
if (bet.result == None):
print("wrong bet")
winloss = -bet.bet_amount
bet.winloss=winloss
bet.result=False
bet.save()
# we dont need to update a loser balance because the amount the lose is already deducted when they lose
def calculate_payout_sport(self):
#WIP
betData=Bets.objects.all()
userData=Users.objects.all()
today = datetime.date.today()
teams = hockeyTeams(year=2021)
#hockey
today = datetime.date.today()
teams = hockeyTeams(year=2021)
Hockey_ID = "3"
Hockey_Game_Counter =0
for team in teams: # for every team
print("\nTeam 1: ", team.name)
team_1 = team.name
teamSchedule = hockeySchedule(team.abbreviation, year=2021) # get their schedule
for game in teamSchedule: # for every game in their schedule
Hockey_Game_Counter += 1
if (game.datetime.date() < today): # and if that game is in the future
gameID = Hockey_ID + str(Hockey_Game_Counter)
gameID = int(gameID)
print(gameID)
if(int(gameID) == 373):
print("Game ID Sport:", gameID)
if(game.result == 'Win'):
winner = team_1
print("winner:", winner)
else:
winner = game.opponent_name
print("winner:", winner)
if (winner == None):
print("No winner")
for bet in betData:
if (bet.game_ID == gameID):
bet.winloss=0
bet.save()
else:
for bet in betData:
if (int(gameID) == 373):
print(bet.game_ID)
if (bet.game_ID == gameID):
if (bet.team_bet == winner):
if (bet.result == None):
print("Correct bet")
winloss = (bet.bet_odds * bet.bet_amount)
bet.winloss=winloss
bet.result=True
bet.save()
for user in userData:
print("Username", user.username)
print("bet user", bet.username)
if (bet.username == user.username):
print(user.username)
newbalance = user.balance + winloss
print(newbalance)
user.balance=newbalance
user.save()
else:
if (bet.result == None):
print("wrong bet")
winloss = -bet.bet_amount
bet.winloss=winloss
bet.result=False
bet.save()
# Basketball payout
today = datetime.date.today()
teams = basketballTeams(year=2021)
Bball_ID = "2"
Bball_Game_Counter = 0
for team in teams:
print("\nTeam 1: ", team.name)
team_1 = team.name
teamSchedule = basketballSchedule(team.abbreviation, year=2021)
for game in teamSchedule:
Bball_Game_Counter += 1
if (game.datetime.date() < today):
gameID = Bball_ID + str(Bball_Game_Counter)
gameID = int(gameID)
if (game.result == 'Win'):
winner = team_1
else:
winner = game.opponent_name
if (winner == None):
print("No winner")
for bet in betData:
if (bet.game_ID == gameID):
bet.winloss=0
bet.save()
else:
for bet in betData:
if (bet.game_ID == gameID):
if (bet.team_bet == winner):
if (bet.result == None):
print("Correct bet")
winloss = (bet.bet_odds * bet.bet_amount)
bet.winloss=winloss
bet.result=True
bet.save()
for user in userData:
print("Username", user.username)
print("bet user", bet.username)
if (bet.username == user.username):
print(user.username)
newbalance = user.balance + winloss
print(newbalance)
user.balance=newbalance
user.save()
else:
if (bet.result == None):
print("wrong bet")
winloss = -bet.bet_amount
bet.winloss=winloss
bet.result=False
bet.save()
#baseball payout
today = datetime.date.today()
teams = baseballTeams(year=2021)
Baseball_ID = "1"
Baseball_Game_Counter = 0
for team in teams:
print("\nTeam 1: ", team.name)
team_1 = team.name
teamSchedule = baseballSchedule(team.abbreviation, year=2021)
for game in teamSchedule:
Baseball_Game_Counter += 1
if (today > game.datetime.date()):
gameID = Baseball_ID + str(Baseball_Game_Counter)
gameID = int(gameID)
if (game.result == 'Win'):
winner = team_1
else:
winner = game.opponent_abbr
if (winner == None):
print("No winner")
for bet in betData:
if (bet.game_ID == gameID):
bet.winloss=0
bet.save()
else:
for bet in betData:
if (bet.game_ID == gameID):
if (bet.team_bet == winner):
if (bet.result == None):
print("Correct bet")
winloss = (bet.bet_odds * bet.bet_amount)
bet.winloss=winloss
bet.result=True
bet.save()
for user in userData:
print("Username", user.username)
print("bet user", bet.username)
if (bet.username == user.username):
print(user.username)
newbalance = user.balance + winloss
print(newbalance)
user.balance=newbalance
user.save()
else:
if (bet.result == None):
print("wrong bet")
winloss = -bet.bet_amount
bet.winloss=winloss
bet.result=False
bet.save()
def get_api_data(self):
print("Getting API DATA")
# Clear games data table
Games.objects.all().delete()
# Hockey
today = datetime.date.today()
teams = hockeyTeams(year=2021)
Hockey_ID = "3"
Hockey_Game_Counter =0
# Game_data = Games(name="<NAME>", time_data=datetime.datetime.strptime('2021-02-27',"%Y-%m-%d"), sport='Hockey', team1="Vegas Gold<NAME>", team1_amount=0,
# team1_odds=1.5, team2="<NAME>", team2_amount=0, team2_odds=1.5, match_id="373")
# Game_data.save()
for team in teams: # for every team
print("\nTeam 1: ", team.name)
team_1 = team.name
teamSchedule = hockeySchedule(team.abbreviation, year=2021) # get their schedule
for game in teamSchedule: # for every game in their schedule
Hockey_Game_Counter += 1
if (game.datetime.date() > today): # and if that game is in the future
add_to_list = True # flag it so it will be added to the database
startTime = game.datetime # set the time
print(game.datetime)
team_2 = game.opponent_name # get their opponent from the API
gameName = team_1 + " " + team_2 + " " + str(game.datetime.date()) # append the two teams and game date
# check for duplicate matches
for each in Games.objects.all(): # for each game in the database
if (each.team1 == team_2 and each.team2 == team_1 and each.time_data == startTime): # if that game as the same 2 teams and startTime
add_to_list = False #we conclude its in the database, and set the flag for it to be added to False
#now we add all new games to the database
if (add_to_list != False):
print("\nTeam 2: ", team.name)
print("\nStarting time", startTime)
Game_data = Games()
Game_ID = Hockey_ID + str(Hockey_Game_Counter)
Game_data = Games(name=gameName, time_data=startTime, sport='Hockey', team1=team_1, team1_amount=0, team1_odds=1.5, team2=team_2, team2_amount=0, team2_odds=1.5, match_id=Game_ID)
Game_data.save()
print("\ndata added")
add_to_list = True
# Basketball
today = datetime.date.today()
teams = basketballTeams(year=2021)
Bball_ID = "2"
Bball_Game_Counter = 0
for team in teams:
print("\nTeam 1: ", team.name)
team_1 = team.name
teamSchedule = basketballSchedule(team.abbreviation, year=2021)
for game in teamSchedule:
Bball_Game_Counter += 1
if (game.datetime.date() > today):
add_to_list = True
startTime = game.datetime
print(game.datetime)
team_2 = game.opponent_name
gameName = team_1 + " " + team_2 + " " + str(game.datetime.date())
# check for duplicate matches
for each in Games.objects.all():
if (each.team1 == team_2 and each.team2 == team_1 and each.time_data == startTime):
add_to_list = False
if (add_to_list != False):
print("\nTeam 2: ", team.name)
print("\nStarting time", startTime)
Game_ID = Bball_ID + str(Bball_Game_Counter)
Game_data = Games(name=gameName, time_data=startTime, sport='BasketBall', team1=team_1, team1_amount=0, team1_odds=1.5, team2=team_2, team2_amount=0, team2_odds=1.5, match_id=Game_ID)
Game_data.save()
print("\ndata added")
add_to_list = True
# Baseball
today = datetime.date.today()
month = timedelta(days=+30)
monthlater = today+month
teams = baseballTeams(year=2021)
Baseball_ID = "1"
Baseball_Game_Counter = 0
for team in teams:
print("\nTeam 1: ", team.name)
team_1 = team.name
teamSchedule = baseballSchedule(team.abbreviation, year=2021)
for game in teamSchedule:
Baseball_Game_Counter += 1
if (today<game.datetime.date() and game.datetime.date()<monthlater):
add_to_list = True
startTime = game.datetime
print(game.datetime)
team_2 = game.opponent_abbr
gameName = team_1 + " " + team_2 + " " + str(game.datetime.date())
# check for duplicate matches
for each in Games.objects.all():
if (each.team1 == team_2 and each.team2 == team_1 and each.time_data == startTime):
add_to_list = False
if (add_to_list != False):
print("\nTeam 2: ", team.name)
print("\nStarting time", startTime)
Game_ID = Baseball_ID + str(Baseball_Game_Counter)
Game_data = Games(name=gameName, time_data=startTime, sport='baseball', team1=team_1, team1_amount=0, team1_odds=1.5, team2=team_2, team2_amount=0, team2_odds=1.5, match_id=Game_ID)
Game_data.save()
print("\ndata added")
add_to_list = True
# League of Legends | LOL
link_lol = 'https://api.pandascore.co/lol/matches/upcoming?token=<KEY>WpjIo21rk0cg'
r_lol = requests.get(link_lol)
data_lol = json.loads(r_lol.text)
print(data_lol[0])
for game in data_lol:
print("\n\nLOL")
gameName = game['name']
print("\nMatch name:", gameName)
gameID = game['id']
print("\nMatch ID:", gameID)
gameFinished = game['status']
print("\nMatch status", gameFinished)
startTime = game['scheduled_at']
startTime = startTime.split('T')
startTime[1] = startTime[1].split('Z')[0]
time = startTime[0] + " " + startTime[1]
print("\nStarting time", startTime)
teams = game['opponents']
if (len(teams) == 2):
team_1 = teams[0]['opponent']['name']
print(team_1)
team_2 = teams[1]['opponent']['name']
print(team_2)
Game_data = Games(name=gameName, time_data=time, sport='LOL', team1=team_1, team1_amount=0, team1_odds=1.5, team2=team_2, team2_amount=0, team2_odds=1.5, match_id=gameID)
Game_data.save()
print("\n")
print("\nDONE WITH LOL")
# DOTA 2
link_dota = 'https://api.pandascore.co/dota2/matches/upcoming?token=<KEY>'
r_dota = requests.get(link_dota)
data_dota = json.loads(r_dota.text)
print(data_dota[0])
for game in data_dota:
print("\ndota2")
gameName = game['name']
print("\nMatch name:", gameName)
gameID = game['id']
print("\nMatch ID:", gameID)
gameFinished = game['status']
print("\nMatch status", gameFinished)
startTime = game['scheduled_at']
startTime = startTime.split('T')
startTime[1] = startTime[1].split('Z')[0]
time=startTime[0] + " " + startTime[1]
print("\nStarting time", startTime)
teams = game['opponents']
if (len(teams) == 2):
team_1 = teams[0]['opponent']['name']
print(team_1)
team_2 = teams[1]['opponent']['name']
print(team_2)
Game_data = Games(name=gameName, time_data=time, sport='dota2', team1=team_1, team1_amount=0, team1_odds=1.5, team2=team_2, team2_amount=0, team2_odds=1.5, match_id=gameID)
Game_data.save()
print("\n")
print("\nDONE WITH DOTA2")
# CSGO
link_CSGO = 'https://api.pandascore.co/csgo/matches/upcoming?token=<KEY>'
r_CSGO = requests.get(link_CSGO)
data_CSGO = json.loads(r_CSGO.text)
print(data_CSGO)
for game in data_CSGO:
print("\nCSGO")
gameName = game['name']
print("\nMatch name:", gameName)
gameID = game['id']
print("\nMatch ID:", gameID)
gameFinished = game['status']
print("\nMatch status", gameFinished)
startTime = game['scheduled_at']
startTime = startTime.split('T')
startTime[1] = startTime[1].split('Z')[0]
print("\nStarting time", startTime)
teams = game['opponents']
if (len(teams) == 2):
team_1 = teams[0]['opponent']['name']
print(team_1)
team_2 = teams[1]['opponent']['name']
print(team_2)
Game_data = Games(name=gameName, time_data=time, sport='CSGO', team1=team_1, team1_amount=0, team1_odds=1.5, team2=team_2, team2_amount=0, team2_odds=1.5, match_id=gameID)
Game_data.save()
print("\n")
print("\nDONE WITH CSGO")
return
def DotaRank(self):
# DOTA Player data
DotaPlayerRanking.objects.all().delete()
link_players = 'https://api.opendota.com/api/rankings'
r_players = requests.get(link_players)
data_players = json.loads(r_players.text)
print(data_players)
players = data_players['rankings']
for player in players:
name = player['personaname']
score = player['score'] # temporarily 1 for everyone, as getting this value isn't as simple as the rest
steamid = player['account_id']
avatar_link = player['avatar']
player_data = DotaPlayerRanking(name=name, rank=score, steamid=steamid,avatar=avatar_link)
player_data.save()
print("added rank data")
# ++count
print("DONE WITH DOTA PLAYER RANKINGS")
return
<file_sep>/hello/migrations/0007_odds.py
# Generated by Django 3.2 on 2021-04-29 16:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0006_auto_20210425_1349'),
]
operations = [
]
<file_sep>/hello/signUp/urls.py
from django.urls import path
from . import views
#sign UP
urlpatterns = [
path('home/Sign Up.html', views.signUp, name='signUp')
]<file_sep>/hello/migrations/0008_auto_20210429_1212.py
# Generated by Django 3.2 on 2021-04-29 17:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hello', '0007_odds'),
]
operations = [
migrations.AddField(
model_name='games',
name='match_id',
field=models.PositiveIntegerField(null=True),
),
migrations.AddField(
model_name='users',
name='balance',
field=models.PositiveIntegerField(null=True),
),
]
<file_sep>/hello/admin.py
from django.contrib import admin
from .models import *
admin.site.register(Users)
admin.site.register(Games)
admin.site.register(Rewards)
admin.site.register(Bets)
admin.site.register(DotaPlayerRanking)
|
e3d6730a47d36f6acc5b0d713a8709e9c441aaa1
|
[
"Python",
"Text"
] | 28
|
Python
|
rpickett0173/papergainz
|
617b72f76e24b216f45a181b0fb03ea2dd4d67e2
|
cb7dd4f8c743a40b2de68dd20593c9b51158b1fe
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.HTML_classes;
namespace ChtemeleSurfaceApplication.Carte_classes
{
public class HTMLTagCarte : HTMLCarte
{
private string _tag;
private HtmlTag.HTMLTagType _tagtype;
public HTMLTagCarte(string tag, HtmlTag.HTMLTagType type, int score, bool textEdit)
: base(score)
{
_tag = tag;
_tagtype = type;
_textEdit = textEdit;
}
public HtmlTag.HTMLTagType getTagtype() { return _tagtype; }
public string getTag() { return _tag; }
public override void onValid()
{
if (_tagtype == HtmlTag.HTMLTagType.OPENTAG)
{
HtmlElement._currentElement = new HtmlElement(_tag);
HtmlElement._currentElement.addContent(new HtmlText(textcontent));
Game_classes.Game.getInstance.getPage().bodyTag().addContent(HtmlElement._currentElement);
}
else
{
if (HtmlElement._currentElement == null) return;
if (HtmlElement._currentElement.getTagname() == _tag)
HtmlElement._currentElement.closeTag();
}
Game_classes.Game.getInstance.getCurPlayer().addPoint(_score);
Game_classes.Game.getInstance.getCurPlayer().lastCombo().addCard(this);
}
public override void onPlay() { }
public override void onDelete() { }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using Microsoft.Surface.Presentation.Controls;
using Microsoft.Surface.Presentation.Generic;
using System.Media;
using ChtemeleSurfaceApplication.Game_classes;
namespace ChtemeleSurfaceApplication
{
/// <summary>
/// Logique d'interaction pour ZoneJoueur.xaml
/// </summary>
public partial class ZoneJoueur : ScatterViewItem
{
// Constantes, enumérations ======================================================================================================
// Variables membres ======================================================================================================
public bool active = false;
private Timer timerIndicator;
// Constructeurs ======================================================================================================
public ZoneJoueur()
{
InitializeComponent();
ButtonNextPlayer.IsEnabled = false;
timerIndicator = new Timer();
timerIndicator.Interval = 6000;
timerIndicator.Tick += new EventHandler(OnTimedEvent_IndicatorDissappear);
}
// Evénements ======================================================================================================
private void ButtonNextPlayer_Click(object sender, RoutedEventArgs e)
{
SurfaceWindow1.getInstance.getMdl.nextSubStep();
SurfaceWindow1.getInstance.updateRotation();
SurfaceWindow1.getInstance.updateZonesJoueur();
SurfaceWindow1.getInstance.updateStepIndicator();
SurfaceWindow1.getInstance.indicatorCurrentPlayer(IndicatorMessages.YOUR_TURN);
Sounder.playCurrentPlayerSound();
}
private void OnTimedEvent_IndicatorDissappear(object source, EventArgs e)
{
ScatterIndicator.Visibility = System.Windows.Visibility.Collapsed;
ScatterIndicator.IsEnabled = false;
timerIndicator.Stop();
}
// Fonctionnalités ======================================================================================================
public void showIndicator(string text)
{
Indicator.Text = text;
ScatterIndicator.Visibility = System.Windows.Visibility.Visible;
ScatterIndicator.IsEnabled = true;
timerIndicator.Stop();
timerIndicator.Start();
}
public void showEffectsIndicator()
{
string msg = "";
foreach (Effect effect in CarteJoueur.getMdl.getPlayer().effects())
{
if (effect is Effect_classes.BrowserUpdate)
msg += IndicatorMessages.BROWSER_UPDATE_EFFECT + '\n';
else if (effect is Effect_classes.CrashBrowser)
msg += IndicatorMessages.CRASH_BROWSER_EFFECT + '\n';
else if (effect is Effect_classes.Freeze)
msg += IndicatorMessages.FREEZE_EFFECT + '\n';
}
if (msg.Length != 0)
SurfaceWindow1.getInstance.indicatorAt(msg, CarteJoueur.getMdl.getPlayer());
}
// Update ======================================================================================================
public void update()
{
if (active)
{
ButtonNextPlayer.IsEnabled = true;
ButtonNextPlayer.Visibility = System.Windows.Visibility.Visible;
Background = new SolidColorBrush(Colors.Transparent);
}
else
{
ButtonNextPlayer.IsEnabled = false;
ButtonNextPlayer.Visibility = System.Windows.Visibility.Collapsed;
Background = new SolidColorBrush(Colors.RosyBrown);
SurfaceWindow1.getInstance.CenterView.Visibility = System.Windows.Visibility.Visible;
}
CarteJoueur.update();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Contient les différentes chaines de texte qui peuvent être affichées dans l'indicateur
/// </summary>
public static class IndicatorMessages
{
public const string YOUR_TURN = "C'est à vous de jouer !";
public const string BROWSER_UPDATE_TOOLTIP = "Browser Update : Au prochain tour vous piochez 2 cartes de plus.";
public const string CRASH_BROWSER_TOOLTIP = "Crash Browser : Au prochain tour vous piocherez 4 cartes de moins.";
public const string FREEZE_TOOLTIP = "Freeze : Vous passerez votre prochain tour.";
public const string BROWSER_UPDATE_EFFECT = "Browser Update : Piochez 2 cartes de plus.";
public const string CAFE_EFFECT = "Piochez jusqu'à avoir 10 cartes en main.";
public const string CODE_INSPECTOR_EFFECT = "Regardez les 4 cartes du dessus de la pioche, mettez-en 2 dans votre main et le reste sur la pioche dans l'ordre de votre choix.";
public const string CTRL_F5_EFFECT = "Défaussez-vous de toutes vos cartes et repiochez-en autant.";
public const string CRASH_BROWSER_EFFECT = "Crash Browser : Piochez 4 cartes de moins.";
public const string ERROR303_EFFECT = "Échangez votre main avec celle de {0}";
public const string ERROR403_EFFECT = "Regardez les cartes de {0} et défaussez-en jusqu'à 6.";
public const string ERROR404_EFFECT = "Vous perdez {0} points.";
public const string FREEZE_EFFECT = "Freeze : Vous passez votre tour.";
public const string MAN_IN_THE_MIDDLE_EFFECT = "Regardez les cartes de {0} et volez-lui en jusqu'à 2.";
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.Fabriques;
using ChtemeleSurfaceApplication.Carte_classes.Addons;
using ChtemeleSurfaceApplication.Carte_classes.Attaques;
using ChtemeleSurfaceApplication.Carte_classes;
using ChtemeleSurfaceApplication.HTML_classes;
using ChtemeleSurfaceApplication.Modeles;
namespace ChtemeleSurfaceApplication
{
public abstract class Carte
{
// Constantes, enumérations ======================================================================================================
public enum TypeCarte
{
HTML_TAG_CARD,
HTML_ATTRIB_CARD,
ATTACK_CARD,
ADDON_CARD,
CARD // Celui-ci est abstrait, il ne doit pas être utilisé hors de la classe Carte.
}
// Variables membres ======================================================================================================
protected string _description;
protected bool _textEdit;
protected bool _imageEdit;
protected TypeCarte _type;
// Constructeurs ======================================================================================================
public Carte()
{
loadDescription();
_textEdit = false;
_imageEdit = false;
_type = TypeCarte.CARD;
}
// Fonctionnalités ======================================================================================================
public abstract void onPlay();
public abstract void onValid();
public abstract void onDelete();
public void loadDescription()
{
}
// Accesseurs / Mutateurs ======================================================================================================
public bool getTextEdit() { return _textEdit; }
public bool getImageEdit() { return _imageEdit; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ChtemeleSurfaceApplication.HTML_classes;
namespace ChtemeleSurfaceApplication.Modeles
{
public class MdlRenduHtml : Modele
{
// Constantes, enumérations ======================================================================================================
// Variables membres ======================================================================================================
private HtmlPage _page; //Données du modèle
private string _code; //Code généré
private int _indentLevel;
private int indentSize = 4;
private int computedIndentChanges = 0;
// Constructeurs ======================================================================================================
public MdlRenduHtml()
: base()
{
_page = _game.getPage();
_code = "";
}
// Accesseurs / Mutateurs ======================================================================================================
public string getCode() { return _code; }
// Fonctionnalités ======================================================================================================
// Rendu d'une page HTML
public void renderPage()
{
_code = "";
_code += _page.doctype() + "\n";
_code += renderHtmlElement(_page.mainTag());
autoIndent();
}
// Rendu d'un élément HTML
public string renderHtmlElement(HtmlElement elem)
{
string res = "";
//on détermine le type de balise
bool multiline = HtmlElement.multiLineTags.Exists(v => v == elem.getTagname());
bool monoline = HtmlElement.monoLineTags.Exists(v => v == elem.getTagname());
bool inline = (!multiline && !monoline);
//chaine des attributs
string resattr = "";
if (elem.attributes.Count > 0)
{
foreach (HtmlTagAttribute attr in elem.attributes)
{
resattr += " ";
resattr += renderHtmlTagAttribute(attr);
}
}
//OpenTag
//if (multiline) res += '\n';
res += renderHtmlTag(elem.getOpenTag(), resattr);
//retour à la ligne post-OpenTag multiline
if (multiline) res += '\n';
//content
if (elem.tagContent.Count > 0)
{
foreach (HtmlTagContent e in elem.tagContent)
{
if (e is HtmlElement)
res += renderHtmlElement(e as HtmlElement);
else if (e is HtmlText)
res += renderHtmlText(e as HtmlText);
}
}
//indentation avant les multilines (intent ='' pour les inlines)
if (multiline) res += '\n';
//EndTag
if (elem.isClosed())
res += renderHtmlTag(elem.getEndTag());
//retour à la ligne post-non-inline
if (!inline) res += '\n';
return res;
}
// Rendu d'une balise HTML ouvrante ou fermante
public string renderHtmlTag(HtmlTag tag, string attribs = "")
{
string res = "";
//on insère la balise
res += HtmlTag.openSymbol[tag.getType()];
res += tag.getTagName();
if (tag.getType() == HtmlTag.HTMLTagType.OPENTAG) res += attribs;
res += HtmlTag.endSymbol;
//on met à jour l'indentation
if (HtmlElement.singleTags.Exists(v => v == tag.getTagName()))
{
if (tag.getType() == HtmlTag.HTMLTagType.OPENTAG) _indentLevel++;
else _indentLevel--;
}
return res;
}
public string renderHtmlText(HtmlText txt)
{
string ret = "";
ret += txt.getText();
return ret;
}
public string renderHtmlTagAttribute(HtmlTagAttribute attr)
{
string res = " ";
res += attr.getKey();
res += "=\"";
res += attr.getValue();
res += "\"";
return res;
}
public void autoIndent()
{
_indentLevel = 0;
string res = "";
//On parcout toutes les balises et les retours à la ligne de la séquence.
MatchEvaluator evalLine = new MatchEvaluator(fetchLine);
string linePattern = @"\n+(?<line>.*)";
try
{
res = Regex.Replace(_code, linePattern, evalLine);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
_code = res;
}
private string fetchIndentItem(Match item)
{
string s = item.ToString();
if (Regex.IsMatch(s, @"^<!.+>$")) //Doctype
{
//nothing
}
else if (Regex.IsMatch(s, @"^<(\w+)(\s[^>]*)?>$")) //balise ouvrante
{
if (HtmlElement.singleTags.Exists(v => v == item.Groups["tagname"].ToString()))
{
//balise simple
}
else
computedIndentChanges++;
}
else //if (Regex.IsMatch(s, @"^</\w+>$")) //balise fermante seule
{
computedIndentChanges--;
}
return s;
}
private string fetchLine(Match item)
{
computedIndentChanges = 0;
string s = item.ToString();
string pattern = @"</?(?<tagname>\w+)(\s[^>]*)?>";
MatchEvaluator evalElem = new MatchEvaluator(fetchIndentItem);
try
{
s = Regex.Replace(s, pattern, evalElem);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if (computedIndentChanges < 0)
{
_indentLevel += computedIndentChanges;
if (_indentLevel < 0) _indentLevel = 0;
}
string res = '\n' + new string(' ', indentSize * _indentLevel) + item.Groups["line"].ToString();
if (computedIndentChanges > 0) _indentLevel += computedIndentChanges;
return res;
}
public string loadHTML(string filepath)
{
System.IO.StreamReader file = new System.IO.StreamReader(filepath);
return file.ReadToEnd();
}
public void changeCSS(string cssname)
{
_game.getPage().changeCSS(cssname);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Awesomium.Windows.Controls;
using Microsoft.Surface.Presentation.Controls;
using ChtemeleSurfaceApplication.Modeles;
namespace ChtemeleSurfaceApplication
{
/// <summary>
/// Logique d'interaction pour RenduHTML.xaml
/// </summary>
public partial class RenduHTML : ScatterViewItem
{
// Constantes, enumérations ======================================================================================================
// Variables membres ======================================================================================================
private MdlRenduHtml _mdl;
// Constructeurs ======================================================================================================
public RenduHTML()
{
InitializeComponent();
}
private void RenduHTML_Loaded(object sender, RoutedEventArgs e)
{
_mdl = SurfaceWindow1.getInstance.getMdl.mPageRendu;
//update();
//webControl.Source = new Uri(System.IO.Directory.GetCurrentDirectory() + "/currentHtml.html");
}
// Fonctionnalités ======================================================================================================
// Evénements ======================================================================================================
private void webControl_Loaded(object sender, RoutedEventArgs e)
{
webControl.Source = new Uri(System.IO.Directory.GetCurrentDirectory() + "\\currentHtml.html");
}
private void CssChangerChtemele_Click(object sender, RoutedEventArgs e)
{
_mdl.changeCSS("chtemele");
SurfaceWindow1.getInstance.updateCodeView();
}
private void CssChangerDark_Click(object sender, RoutedEventArgs e)
{
_mdl.changeCSS("dark");
SurfaceWindow1.getInstance.updateCodeView();
}
private void CssChangerLight_Click(object sender, RoutedEventArgs e)
{
_mdl.changeCSS("light");
SurfaceWindow1.getInstance.updateCodeView();
}
// Update ======================================================================================================
public void update()
{
webControl.Reload(false);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.Carte_classes.Addons
{
public class Antivirus : AddonCarte
{
public Antivirus() : base(){}
public override void onValid() // Normalement celle-ci est applée automatiquement
{
base.onValid();
Game_classes.Game.getInstance.isThereAntivirus = false;
}
public override void onPlay()
{
base.onPlay();
Game_classes.Game.getInstance.isThereAntivirus = true;
}
public override void onDelete()
{
base.onDelete();
Game_classes.Game.getInstance.isThereAntivirus = false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.Game_classes;
namespace ChtemeleSurfaceApplication
{
class Modele
{
private Game _game;
public Modele()
{
_game = Game.getInstance;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.Game_classes;
namespace ChtemeleSurfaceApplication
{
public abstract class EventCarte : Carte
{
public EventCarte() : base() { }
override public abstract void onPlay();
override public abstract void onValid();
override public abstract void onDelete();
public Player target;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.HTML_classes;
namespace ChtemeleSurfaceApplication
{
public abstract class HTMLCarte : Carte
{
// Constantes, enumérations ======================================================================================================
// Variables membres ======================================================================================================
protected int _score; // Score qu'occtroie la carte
protected string _textcontent = ""; // Texte qu'on a inscrit dans la carte
// Constructeurs ======================================================================================================
public HTMLCarte(int s)
: base()
{
_score = s;
}
// Accesseurs & Mutateurs ======================================================================================================
public int score { get { return _score; } }
public string textcontent { get { return _textcontent; } set { _textcontent = value; } }
// Fonctionnalités ======================================================================================================
override public abstract void onPlay();
override public abstract void onValid();
override public abstract void onDelete();
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.Game_classes;
namespace ChtemeleSurfaceApplication.Modeles
{
public class MdlCarteJoueur : Modele
{
// Constantes, enumérations ======================================================================================================
// Variables membres ======================================================================================================
private Player _player; //Données du modèle
// Constructeurs ======================================================================================================
public MdlCarteJoueur(Player p)
: base()
{
_player = p;
}
// Fonctionnalités ======================================================================================================
//a partir de la classe Player
public Player getPlayer() { return _player; }
public string getPlayerName() { return _player.name; }
public void setPlayerName(string n) { _player.name = n; }
public int getPlayerScore() { return _player.score; }
//a partir de la classe Combo
public Combo getCombo() { return _player.lastCombo(); }
public string getComboCode() { return _player.lastCombo().code; }
public bool hasBrowserUpdate()
{
foreach (Effect effect in _player.effects())
{
if (effect.getTypeEffect() == Effect.EffectType.BROWSERUPDATE)
return true;
}
return false;
}
public bool hasCrashBrowser()
{
foreach (Effect effect in _player.effects())
{
if (effect.getTypeEffect() == Effect.EffectType.CRASHBROWSER)
return true;
}
return false;
}
public bool hasFreeze()
{
foreach (Effect effect in _player.effects())
{
if (effect.getTypeEffect() == Effect.EffectType.FREEZE)
return true;
}
return false;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.HTML_classes;
namespace ChtemeleSurfaceApplication.HTML_classes
{
public class HtmlElement : HtmlTagContent
{
public static HtmlElement _currentElement = null;
private string _name;
private bool _isCorrect; // non implémenté
private string _tagname;
public List<HtmlTagAttribute> attributes;
public List<HtmlTagContent> tagContent;
private int _score;
private HtmlTag _openTag;
private HtmlTag _endTag;
private bool _closed = false;
public bool isClosed() { return _closed; }
//options de génération HTML
private static Dictionary<HtmlTag.HTMLTagType, string> openSymbol = new Dictionary<HtmlTag.HTMLTagType, string>
{
{HtmlTag.HTMLTagType.OPENTAG , "<"},
{HtmlTag.HTMLTagType.ENDTAG , "</"}
};
private static string endSymbol = ">";
public static List<string> multiLineTags = new List<string>
{
"html", "head", "body", "p", "div", "blockquote", "header", "footer", "aside", "hr", "img"
};
public static List<string> monoLineTags = new List<string>
{
"h1", "h2", "h3", "h4", "h5", "h6", "br", "link", "meta", "title"
};
public static List<string> singleTags = new List<string>
{
"br", "hr", "img", "link", "meta"
};
public HtmlElement(string name)
: base()
{
_name = name;
_isCorrect = false;
_score = 0;
_tagname = name;
attributes = new List<HtmlTagAttribute>();
tagContent = new List<HtmlTagContent>();
openTag();
}
public string getTagname() { return _tagname; }
public HtmlTag getOpenTag() { return _openTag; }
public HtmlTag getEndTag() { return _endTag; }
public void closeTag()
{
_endTag = new HtmlTag(_tagname, HtmlTag.HTMLTagType.ENDTAG);
_closed = true;
}
public void openTag()
{
_openTag = new HtmlTag(_tagname, HtmlTag.HTMLTagType.OPENTAG);
_closed = false;
}
public void addContent(HtmlTagContent c)
{
tagContent.Add(c);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.Game_classes;
namespace ChtemeleSurfaceApplication.Modeles
{
public class MdlGame : Modele
{
// Constantes, enumérations ======================================================================================================
public const string DEFAULT_HTMLCODE_FILEPATH = "./currentHtml.html";
// Variables membres ======================================================================================================
//Modèles fils
MdlCarteJoueur _mCarteS, _mCarteO, _mCarteN, _mCarteE;
MdlPageCode _mPageCode;
MdlRenduHtml _mPageRendu;
//MdlTag _mTag;
//Dictionary<int, MdlTag> _mTags = new Dictionary<int, MdlTag>();
//Membres
string _htmlFilePath; // chemin vers le fichier de sauvegarde du code
string _gameFilePath; // chemin vers le fichier de sauvegarde de la partie
// Constructeurs ======================================================================================================
public MdlGame()
: base()
{
_mCarteS = new MdlCarteJoueur(_game.playerS);
_mCarteO = new MdlCarteJoueur(_game.playerO);
_mCarteN = new MdlCarteJoueur(_game.playerN);
_mCarteE = new MdlCarteJoueur(_game.playerE);
_mPageCode = new MdlPageCode();
_mPageRendu = new MdlRenduHtml();
_htmlFilePath = DEFAULT_HTMLCODE_FILEPATH;
}
// Accesseurs & Mutateurs ======================================================================================================
public MdlCarteJoueur mCarteS { get { return _mCarteS; } }
public MdlCarteJoueur mCarteO { get { return _mCarteO; } }
public MdlCarteJoueur mCarteN { get { return _mCarteN; } }
public MdlCarteJoueur mCarteE { get { return _mCarteE; } }
public MdlPageCode mPageCode { get { return _mPageCode; } }
public MdlRenduHtml mPageRendu { get { return _mPageRendu; } }
public string htmlFilePath { get { return _htmlFilePath; } set { _htmlFilePath = value; } }
void setGameFilePath(string s) { _gameFilePath = s; }
//void setHtmlFilePath(string s) { _htmlFilePath = s; }
// Fonctionnalités ======================================================================================================
public int getCurrentStep() { return _game.getCurrentStep(); }
public int getTotalStep() { return _game.getTotalSteps(); }
public void setNbPlayer(int n) { _game.setNbPlayer(n); }
public bool saveGame()
{
return false;
}
public bool loadGame()
{
return false;
}
/// <summary>
/// Retourne à quelle position est située le navigateur passé en paramètre
/// </summary>
/// <param name="nav">L'id du navigateur à trouver (Player.__constante__)</param>
/// <returns>Player.NORD|SUD|EST|OUEST ou Player.OUT si le navigateur n'est pas en jeu.</returns>
public int getBrowserPosition(int nav){
if (_game.LocationNav.ContainsKey(nav))
return _game.LocationNav[nav];
else
return Player.OUT;
}
public void setBrowserPosition(int nav, int pos)
{
_game.LocationNav[nav] = pos;
}
public void newPlayer(Player p)
{
if (getPlayerAt(p.position()) == null)
{
_game.setPlayer(p, p.position());
switch (p.position())
{
case Player.SUD: _mCarteS = new MdlCarteJoueur(p); break;
case Player.OUEST: _mCarteO = new MdlCarteJoueur(p); break;
case Player.NORD: _mCarteN = new MdlCarteJoueur(p); break;
case Player.EST: _mCarteE = new MdlCarteJoueur(p); break;
default: break;
}
}
}
public Player getPlayerAt(int pos)
{
switch (pos)
{
case Player.SUD: return _game.playerS;
case Player.OUEST: return _game.playerO;
case Player.NORD: return _game.playerN;
case Player.EST: return _game.playerE;
default: return null;
}
}
public void initGame()
{
_game.initGame();
}
/// <summary>
/// Termine le tour du joueur actuel
/// </summary>
public void nextSubStep()
{
bool toPass = false;
_game.nextPlayer();
SurfaceWindow1.getInstance.getCurrentPlayerZone().showEffectsIndicator();
if (_game.getCurPlayer().isFrozen()) toPass = true;
_game.getCurPlayer().applyEffects();
if (toPass) nextSubStep();
}
public Player getCurrentPlayer()
{
return _game.getCurPlayer();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication
{
public abstract class AddonCarte : EventCarte
{
public AddonCarte() : base() { }
override public void onPlay() { }
override public void onValid() { }
override public void onDelete() { }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication
{
public abstract class AttaqueCarte : EventCarte
{
public AttaqueCarte() : base() { }
override public void onPlay() { }
override public void onValid() { }
override public void onDelete() { }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.File_classes
{
class FileWriter
{
// Variable contenant le code basic d'une page HTML5
public string basicHTML5code =
"<!DOCTYPE html><html><head><meta charset='UTF-8'><title>Title of the document</title></head><body>Content of the document......</body></html>";
// Ecrit un string après UN ou DES caractères de délimitation
// FileUrl -> chemin local absolu vers le fichier
// string[] textToWrite -> permet d'enregistrer plusieurs lignes
public void writeInFile(string FileUrl, string textToWrite, string delimitation)
{
System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(FileUrl, true); // Writer
string[] lines = System.IO.File.ReadAllLines(FileUrl); // Reader
// lire le fichier jusqu'à rencontrer la délimitation
for (int i = 0; i < lines.Length; i++)
{
if (lines[i] == delimitation)
{
// écrit le texte demandé à la ligne
fileWriter.WriteLine(textToWrite);
}
}
}
public void writeBasicHTML5Code(string fileUrl)
{
string delimitation = "";
writeInFile(fileUrl, basicHTML5code,delimitation);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.Carte_classes.Attaques
{
public class ManInTheMiddle : AttaqueCarte
{
public ManInTheMiddle() : base() { }
public override void onValid()
{
// Elfe airien
}
public override void onPlay() { }
public override void onDelete() { }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Surface.Presentation.Controls;
namespace ChtemeleSurfaceApplication
{
/// <summary>
/// Logique d'interaction pour PageDoc.xaml
/// </summary>
public partial class PageDoc : ScatterViewItem
{
// contient l'URL de l'index de la documentation
public string DocUrl;
public PageDoc()
{
InitializeComponent();
// Initialise l'adresse de la doc
DocUrl = System.IO.Directory.GetCurrentDirectory();
DocUrl = DocUrl + "/Resources/Documentation/index.html";
webControl.Source = new Uri(DocUrl);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.HTML_classes
{
public class HtmlTag
{
public enum HTMLTagType {OPENTAG, ENDTAG};
private string _tagname;
private HTMLTagType _type;
//options de génération HTML
public static Dictionary<HtmlTag.HTMLTagType, string> openSymbol = new Dictionary<HtmlTag.HTMLTagType, string>
{
{HtmlTag.HTMLTagType.OPENTAG , "<"},
{HtmlTag.HTMLTagType.ENDTAG , "</"}
};
public static string endSymbol = ">";
/// <summary>
/// Constructor
/// </summary>
/// <param name="tag"></param>
/// <param name="type"></param>
public HtmlTag(string tag, HTMLTagType type)
{
_tagname = tag;
_type = type;
}
public string getTagName() { return _tagname; }
public HTMLTagType getType() { return _type; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.HTML_classes
{
public class HtmlText : HtmlTagContent
{
private string _str;
public HtmlText(string str)
: base()
{
_str = str;
}
public string getText() { return _str; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.Game_classes;
namespace ChtemeleSurfaceApplication.Modeles
{
public class Modele
{
protected Game _game;
public Modele()
{
_game = Game.getInstance;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
//using System.Drawing;
using Microsoft.Surface.Presentation.Controls;
using ChtemeleSurfaceApplication.Game_classes;
using ChtemeleSurfaceApplication.Modeles;
namespace ChtemeleSurfaceApplication
{
/// <summary>
/// Logique d'interaction pour CartesJoueurs.xaml
/// </summary>
public partial class CartesJoueurs : ScatterViewItem
{
// Constantes, enumérations ======================================================================================================
public static int tailleW = 300;
public static int tailleH = 150;
// Variables membres ======================================================================================================
private MdlCarteJoueur _mdl;
public MdlCarteJoueur getMdl { get { return _mdl; } }
public int position;
private static int nbCarteJoueurActiv;
// Constructeurs ======================================================================================================
public CartesJoueurs()
{
InitializeComponent();
//cacher gride1 pour choix navigateur
CarteJoueurGrid.Visibility = System.Windows.Visibility.Hidden;
ChoixNav.Visibility = System.Windows.Visibility.Visible;
CarteJoueurGrid.IsEnabled = false;
ChoixNav.IsEnabled = true;
// Au départ, aucun modèle car aucun joueur.
_mdl = null;
position = 0;
nbCarteJoueurActiv = 0;
// image effect cacher au départ
EffectBrowserUpdate.Visibility = System.Windows.Visibility.Hidden;
EffectCrashBrowser.Visibility = System.Windows.Visibility.Hidden;
EffectFreeze.Visibility = System.Windows.Visibility.Hidden;
}
private void CartesJoueurs_Loaded(object sender, RoutedEventArgs e)
{
// Nothing pour le moment
}
// Fonctionnalités ======================================================================================================
// Associe un nouveau joueur à la CarteJoueur
public void ChoixNavigateur(int positionJoueur, int navClicked)
{
// Si le navigateur sélectionné a déjà été pris, on se barre direct.
if (SurfaceWindow1.getInstance.getMdl.getBrowserPosition(navClicked) != Player.OUT)
{
return;
}
// On dit à Game que ce navigateur est désormais pris.
Game.getInstance.LocationNav[navClicked] = positionJoueur;
//On créée le nouveau joueur
SurfaceWindow1.getInstance.getMdl.newPlayer(new Player(Player.browserNames[navClicked], positionJoueur, navClicked));
SurfaceWindow1.getInstance.getMdl.setBrowserPosition(navClicked, positionJoueur);
switch (positionJoueur)
{
case Player.SUD: _mdl = SurfaceWindow1.getInstance.getMdl.mCarteS; break;
case Player.OUEST: _mdl = SurfaceWindow1.getInstance.getMdl.mCarteO; break;
case Player.NORD: _mdl = SurfaceWindow1.getInstance.getMdl.mCarteN; break;
case Player.EST: _mdl = SurfaceWindow1.getInstance.getMdl.mCarteE; break;
default: _mdl = null; break;
}
foreach (KeyValuePair<int, CartesJoueurs> carte in SurfaceWindow1.tabCartes)
{
for (int i = 0; i < 5; i++)
{
if (i == navClicked)
{
switch (i)
{
case 0: carte.Value.BtnNav0.IsEnabled = false;
break;
case 1: carte.Value.BtnNav1.IsEnabled = false;
break;
case 2: carte.Value.BtnNav2.IsEnabled = false;
break;
case 3: carte.Value.BtnNav3.IsEnabled = false;
break;
case 4: carte.Value.BtnNav4.IsEnabled = false;
break;
}
}
}
}
// On déactive le choix de navigateur et on active la carte Joueur
ChoixNav.IsEnabled = false;
ChoixNav.Visibility = System.Windows.Visibility.Hidden;
CarteJoueurGrid.IsEnabled = true;
CarteJoueurGrid.Visibility = System.Windows.Visibility.Visible;
// Update final
update();
}
// Evénements ======================================================================================================
// Clic sur les boutons de choix de navigateur
private void SurfaceButton_Click0(object sender, RoutedEventArgs e)
{
ChoixNavigateur(position, Player.FIREFOX);
_mdl.setPlayerName(Player.browserNames[Player.FIREFOX]);
}
private void SurfaceButton_Click1(object sender, RoutedEventArgs e)
{
ChoixNavigateur(position, Player.CHROME);
_mdl.setPlayerName(Player.browserNames[Player.CHROME]);
}
private void SurfaceButton_Click2(object sender, RoutedEventArgs e)
{
ChoixNavigateur(position, Player.IE);
_mdl.setPlayerName(Player.browserNames[Player.IE]);
}
private void SurfaceButton_Click3(object sender, RoutedEventArgs e)
{
ChoixNavigateur(position, Player.SAFARI);
_mdl.setPlayerName(Player.browserNames[Player.SAFARI]);
}
private void SurfaceButton_Click4(object sender, RoutedEventArgs e)
{
ChoixNavigateur(position, Player.OPERA);
_mdl.setPlayerName(Player.browserNames[Player.OPERA]);
}
//Fonction click afin d'afficher la popup de description de chaque effect
private void EffectBrowserUpdate_Click(object sender, RoutedEventArgs e)
{
//PopUpEffectBrowserUpdate.Visibility = System.Windows.Visibility.Visible;
//timer_BrowserUpdate.Enabled = true;
SurfaceWindow1.getInstance.indicatorAt(IndicatorMessages.BROWSER_UPDATE_TOOLTIP, _mdl.getPlayer());
}
private void EffectCrashBrowser_Click(object sender, RoutedEventArgs e)
{
//PopUpEffectCrashBrowser.Visibility = System.Windows.Visibility.Visible;
//timer_CrashBrowser.Enabled = true;
SurfaceWindow1.getInstance.indicatorAt(IndicatorMessages.CRASH_BROWSER_TOOLTIP, _mdl.getPlayer());
}
private void EffectFreeze_Click(object sender, RoutedEventArgs e)
{
//PopUpEffectFreeze.Visibility = System.Windows.Visibility.Visible;
//timer_Freeze.Enabled = true;
SurfaceWindow1.getInstance.indicatorAt(IndicatorMessages.FREEZE_TOOLTIP, _mdl.getPlayer());
}
// Update ======================================================================================================
public void update()
{
//affiche pseudo du joueur
PseudoCarte.Text = _mdl.getPlayerName();
//affiche points du joueur
Points.Text = _mdl.getPlayerScore().ToString();
nbCarteJoueurActiv++;
if (nbCarteJoueurActiv == Game.getInstance.getNbPlayer())
{
SurfaceWindow1.getInstance.getMdl.initGame();
SurfaceWindow1.getInstance.layoutGameStarted();
}
//affiche dernière combinaison de balises posée
Combinaison.Text = _mdl.getComboCode().ToString();
PointsCombo.Text = _mdl.getCombo().score.ToString();
//affichage des effects
if (_mdl.hasBrowserUpdate())
{
EffectBrowserUpdate.Visibility = System.Windows.Visibility.Visible;
EffectBrowserUpdate.IsEnabled = true;
}
else
{
EffectBrowserUpdate.Visibility = System.Windows.Visibility.Hidden;
EffectBrowserUpdate.IsEnabled = false;
}
if (_mdl.hasCrashBrowser())
{
EffectCrashBrowser.Visibility = System.Windows.Visibility.Visible;
EffectCrashBrowser.IsEnabled = true;
}
else
{
EffectCrashBrowser.Visibility = System.Windows.Visibility.Hidden;
EffectCrashBrowser.IsEnabled = false;
}
if (_mdl.hasFreeze())
{
EffectFreeze.Visibility = System.Windows.Visibility.Visible;
EffectFreeze.IsEnabled = true;
}
else
{
EffectFreeze.Visibility = System.Windows.Visibility.Hidden;
EffectFreeze.IsEnabled = false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication
{
class Class_Combo
{
// Numéro du code
private int code;
// ??? Score
private int score;
// Tableau du dernier combo, 12 étant le nb max de carte en main
private int []lastCombo = new int [12];
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.Game_classes;
using ChtemeleSurfaceApplication.Carte_classes;
using ChtemeleSurfaceApplication.Fabriques;
namespace ChtemeleSurfaceApplication.Modeles
{
//Classe qui gère le lien entre le tag, la carte et sa description.
class CarteAssoc
{
// Constantes, enumérations ======================================================================================================
public static Dictionary<int, CarteAssoc> AssocTagCarte = new Dictionary<int, CarteAssoc>
{
// cartes addons
{(int)MdlTag.TagCorrespondance.ANTIVIRUS, new CarteAssoc((int)MdlTag.TagCorrespondance.ANTIVIRUS, FabriqueCarte.CreateAntivirus(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.BROWSER_UPDATE, new CarteAssoc((int)MdlTag.TagCorrespondance.BROWSER_UPDATE, FabriqueCarte.CreateBrowserUpdate(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.CAFE, new CarteAssoc((int)MdlTag.TagCorrespondance.CAFE, FabriqueCarte.CreateCafe(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.CODE_INSPECTOR, new CarteAssoc((int)MdlTag.TagCorrespondance.CODE_INSPECTOR, FabriqueCarte.CreateCodeInspector(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.CTRL_F5, new CarteAssoc((int)MdlTag.TagCorrespondance.CTRL_F5, FabriqueCarte.CreateCtrlF5(), "ba", "ab")},
// cartes attaques
{(int)MdlTag.TagCorrespondance.CRASH_BROWSER, new CarteAssoc((int)MdlTag.TagCorrespondance.CRASH_BROWSER, FabriqueCarte.CreateCrashBrowser(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.ERROR_303, new CarteAssoc((int)MdlTag.TagCorrespondance.ERROR_303, FabriqueCarte.CreateError303(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.ERROR_403, new CarteAssoc((int)MdlTag.TagCorrespondance.ERROR_403, FabriqueCarte.CreateError403(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.ERROR_404, new CarteAssoc((int)MdlTag.TagCorrespondance.ERROR_404, FabriqueCarte.CreateError404(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.FREEZE, new CarteAssoc((int)MdlTag.TagCorrespondance.FREEZE, FabriqueCarte.CreateFreeze(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.MAN_IN_THE_MIDDLE, new CarteAssoc((int)MdlTag.TagCorrespondance.MAN_IN_THE_MIDDLE, FabriqueCarte.CreateManInTheMiddle(), "ba", "ab")},
// cartes ouvrantes
{(int)MdlTag.TagCorrespondance.OPEN_H1, new CarteAssoc((int)MdlTag.TagCorrespondance.OPEN_H1, FabriqueCarte.CreateOpenH1(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.OPEN_H2, new CarteAssoc((int)MdlTag.TagCorrespondance.OPEN_H2, FabriqueCarte.CreateOpenH2(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.OPEN_P, new CarteAssoc((int)MdlTag.TagCorrespondance.OPEN_P, FabriqueCarte.CreateOpenP(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.OPEN_DIV, new CarteAssoc((int)MdlTag.TagCorrespondance.OPEN_DIV, FabriqueCarte.CreateOpenDIV(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.OPEN_BLOCKQUOTE, new CarteAssoc((int)MdlTag.TagCorrespondance.OPEN_BLOCKQUOTE, FabriqueCarte.CreateOpenBLOCKQUOTE(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.OPEN_HEADER, new CarteAssoc((int)MdlTag.TagCorrespondance.OPEN_HEADER, FabriqueCarte.CreateOpenHEADER(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.OPEN_FOOTER, new CarteAssoc((int)MdlTag.TagCorrespondance.OPEN_FOOTER, FabriqueCarte.CreateOpenFOOTER(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.OPEN_ASIDE, new CarteAssoc((int)MdlTag.TagCorrespondance.OPEN_ASIDE, FabriqueCarte.CreateOpenASIDE(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.OPEN_STRONG, new CarteAssoc((int)MdlTag.TagCorrespondance.OPEN_STRONG, FabriqueCarte.CreateOpenSTRONG(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.OPEN_EM, new CarteAssoc((int)MdlTag.TagCorrespondance.OPEN_EM, FabriqueCarte.CreateOpenEM(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.OPEN_A, new CarteAssoc((int)MdlTag.TagCorrespondance.OPEN_A, FabriqueCarte.CreateOpenA(), "ba", "ab")},
// cartes fermantes
{(int)MdlTag.TagCorrespondance.END_H1, new CarteAssoc((int)MdlTag.TagCorrespondance.END_H1, FabriqueCarte.CreateEndH1(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.END_H2, new CarteAssoc((int)MdlTag.TagCorrespondance.END_H2, FabriqueCarte.CreateEndH2(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.END_P, new CarteAssoc((int)MdlTag.TagCorrespondance.END_P, FabriqueCarte.CreateEndP(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.END_DIV, new CarteAssoc((int)MdlTag.TagCorrespondance.END_DIV, FabriqueCarte.CreateEndDIV(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.END_BLOCKQUOTE, new CarteAssoc((int)MdlTag.TagCorrespondance.END_BLOCKQUOTE, FabriqueCarte.CreateEndBLOCKQUOTE(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.END_HEADER, new CarteAssoc((int)MdlTag.TagCorrespondance.END_HEADER, FabriqueCarte.CreateEndHEADER(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.END_FOOTER, new CarteAssoc((int)MdlTag.TagCorrespondance.END_FOOTER, FabriqueCarte.CreateEndFOOTER(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.END_ASIDE, new CarteAssoc((int)MdlTag.TagCorrespondance.END_ASIDE, FabriqueCarte.CreateEndASIDE(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.END_STRONG, new CarteAssoc((int)MdlTag.TagCorrespondance.END_STRONG, FabriqueCarte.CreateEndSTRONG(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.END_EM, new CarteAssoc((int)MdlTag.TagCorrespondance.END_EM, FabriqueCarte.CreateEndEM(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.END_A, new CarteAssoc((int)MdlTag.TagCorrespondance.END_A, FabriqueCarte.CreateEndA(), "ba", "ab")},
// cartes simple
{(int)MdlTag.TagCorrespondance.SINGLE_BR, new CarteAssoc((int)MdlTag.TagCorrespondance.SINGLE_BR, FabriqueCarte.CreateBR(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.SINGLE_HR, new CarteAssoc((int)MdlTag.TagCorrespondance.SINGLE_HR, FabriqueCarte.CreateHR(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.SINGLE_IMG, new CarteAssoc((int)MdlTag.TagCorrespondance.SINGLE_IMG, FabriqueCarte.CreateIMG(), "ba", "ab")},
// cartes attributs
{(int)MdlTag.TagCorrespondance.ATTRIB_HREF, new CarteAssoc((int)MdlTag.TagCorrespondance.ATTRIB_HREF, FabriqueCarte.CreateHREF(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.ATTRIB_SRC, new CarteAssoc((int)MdlTag.TagCorrespondance.ATTRIB_SRC, FabriqueCarte.CreateSRC(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.ATTRIB_ALT, new CarteAssoc((int)MdlTag.TagCorrespondance.ATTRIB_ALT, FabriqueCarte.CreateALT(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.ATTRIB_CLASS, new CarteAssoc((int)MdlTag.TagCorrespondance.ATTRIB_CLASS, FabriqueCarte.CreateCLASS(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.ATTRIB_ID, new CarteAssoc((int)MdlTag.TagCorrespondance.ATTRIB_ID, FabriqueCarte.CreateID(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.ATTRIB_STYLE, new CarteAssoc((int)MdlTag.TagCorrespondance.ATTRIB_STYLE, FabriqueCarte.CreateSTYLE(), "ba", "ab")},
{(int)MdlTag.TagCorrespondance.ATTRIB_TITLE, new CarteAssoc((int)MdlTag.TagCorrespondance.ATTRIB_TITLE, FabriqueCarte.CreateTITLE(), "ba", "ab")}
};
public delegate Carte generateCarte();
// Variables membres ======================================================================================================
public int tag;
public string descriptionFilename;
public string keyword;
public Carte card;
// Constructeurs ======================================================================================================
// Paramètres : t tag
// delegate de construction
// d uri du fichier de description
// k mot-clé de la carte
public CarteAssoc(int t, Carte carte, string d, string k)
{
tag = t;
descriptionFilename = d;
keyword = k;
card = carte;
}
// Accesseurs / Mutateurs ======================================================================================================
public Carte getCarte()
{
return card;
}
}
//======================================================================================================================================
//======================================================================================================================================
//======================================================================================================================================
public class MdlTag : Modele
{
// Constantes, enumérations ======================================================================================================
public enum TagCorrespondance
{
// Cartes Add-ons
ANTIVIRUS = 0x6D,
BROWSER_UPDATE = 0x67,
CAFE = 0x53,
CODE_INSPECTOR = 0x55,
CTRL_F5 = 0x56,
// Cartes Attaques
CRASH_BROWSER = 0x57,
ERROR_303 = 0x59,
ERROR_403 = 0x5B,
ERROR_404 = 0x51,
FREEZE = 0x5E,
MAN_IN_THE_MIDDLE = 0x5F,
// Cartes Balises Ouvrantes
OPEN_H1 = 0x65,
OPEN_H2 = 0x69,
OPEN_P = 0x6A,
OPEN_DIV = 0x6B,
OPEN_BLOCKQUOTE = 0x6F,
OPEN_HEADER = 0x73,
OPEN_FOOTER = 0x75,
OPEN_ASIDE = 0x76,
OPEN_STRONG = 0x77,
OPEN_EM = 0x79,
OPEN_A = 0x7A,
// Cartes Balises Fermantes
END_H1 = 0x7B,
END_H2 = 0x7D,
END_P = 0x7E,
END_DIV = 0x7F,
END_BLOCKQUOTE = 0x9B,
END_HEADER = 0x9D,
END_FOOTER = 0x9E,
END_ASIDE = 0x9F,
END_STRONG = 0xB7,
END_EM = 0xB9,
END_A = 0xBB,
// Cartes Balises Simples
SINGLE_BR = 0xBD,
SINGLE_HR = 0xBE,
SINGLE_IMG = 0xBF,
// Cartes Attributs
ATTRIB_HREF = 0xD7,
ATTRIB_SRC = 0xD9,
ATTRIB_ALT = 0xDB,
ATTRIB_CLASS = 0xDD,
ATTRIB_ID = 0xDF,
ATTRIB_STYLE = 0xE5,
ATTRIB_TITLE = 0xE6
}
public class InfoMessage
{
public const string MULTICARD = "Plusieurs cartes sur la table !";
public const string PLAYED = "Carte jouée, veuillez la défausser.";
public const string GAME_NOT_STARTED = "La partie n'est pas encore commencée.";
public const string CANCELED = "Cette action a été contrée.";
}
public static List<int> ghostList = new List<int>
{
(int)TagCorrespondance.ANTIVIRUS
};
private static int nbCards = 0;
private static int nbGhosts = 0; // Les cartes fantômes sont traitées à part : il peut y avoir une carte fantôme sur la table même s'il y a déjà une carte normale.
// Variables membres ======================================================================================================
private int _tag; // Numéro du Tag
private Carte _card;
private Carte.TypeCarte _typeCard;
//private Player _activePlayer; // On s'en sert pas, normalement, mais je le laisse au cas où j'me sois gourré.
public Player targetPlayer;
public string textContent;
private bool _played = false;
private bool _multicard = false;
private bool _canceled = false;
private bool _isGhost = false;
//Booléens d'affichage de widgets
private bool _hasTextEdit = false;
private bool _hasImageSelector = false;
private bool _hasPlayerSelector = false;
// Constructeurs ======================================================================================================
public MdlTag(int tag)
: base()
{
_tag = tag;
_isGhost = ghostList.Contains(tag);
newTag();
computeMulticard();
}
// Accesseurs / Mutateurs ======================================================================================================
public bool isMulticard() { return _multicard; }
public bool hasTextEdit() { return _hasTextEdit; }
public bool hasImageSelector() { return _hasImageSelector; }
public bool hasPlayerSelector() { return _hasPlayerSelector; }
public Carte card { get { return _card; } }
public Carte.TypeCarte typeCard { get { return _typeCard; } }
public int tag { get { return _tag; } }
public bool canceled { get { return _canceled; } set { _canceled = value; } }
// Fonctionnalités ======================================================================================================
// Nouveau tag détecté et validé (on est en droit de le poser et il est seul sur la table)
public void onTag()
{
//On récupère la carte correspondante
_card = CarteAssoc.AssocTagCarte[_tag].getCarte();
//On détecte le type de la carte
_typeCard = Carte.TypeCarte.CARD;
if (_card is HTMLTagCarte) _typeCard = Carte.TypeCarte.HTML_TAG_CARD;
else if (_card is HTMLAttributeCarte) _typeCard = Carte.TypeCarte.HTML_ATTRIB_CARD;
else if (_card is AddonCarte) _typeCard = Carte.TypeCarte.ADDON_CARD;
else if (_card is AttaqueCarte) _typeCard = Carte.TypeCarte.ATTACK_CARD;
//On détermine le layout à afficher
if ((_typeCard == Carte.TypeCarte.HTML_TAG_CARD && ((HTMLTagCarte)_card).getTagtype() == HTML_classes.HtmlTag.HTMLTagType.OPENTAG) && !HTML_classes.HtmlElement.singleTags.Exists(v => v == ((HTMLTagCarte)_card).getTag()) || _typeCard == Carte.TypeCarte.HTML_ATTRIB_CARD)
_hasTextEdit = true;
if (_typeCard == Carte.TypeCarte.ATTACK_CARD)
_hasPlayerSelector = true;
if (_tag == (int)TagCorrespondance.ATTRIB_SRC)
_hasImageSelector = true;
_card.onPlay();
}
public bool validerCarte()
{
if (!isPlayable()) return false;
//On configure la carte
if (_typeCard == Carte.TypeCarte.ADDON_CARD || _typeCard == Carte.TypeCarte.ATTACK_CARD)
{
((EventCarte)_card).target = targetPlayer;
}
else if (_typeCard == Carte.TypeCarte.HTML_TAG_CARD || _typeCard == Carte.TypeCarte.HTML_ATTRIB_CARD)
{
((HTMLCarte)_card).textcontent = textContent;
}
else if (_tag == (int)TagCorrespondance.ATTRIB_SRC)
{
//obtenir le chemin de l'image
((HTMLAttributeCarte)_card).textcontent = textContent;
}
_card.onValid();
_played = true;
return true;
}
public void onRemoved(){
loseTag();
_card.onDelete();
}
public void computeMulticard()
{
_multicard = nbCards > 1 || nbGhosts > 1;
}
public string getInfoMessage()
{
if (!_game.getGameStarted()) return InfoMessage.GAME_NOT_STARTED;
else if (_multicard) return InfoMessage.MULTICARD;
else if (_played) return InfoMessage.PLAYED;
else if (_canceled) return InfoMessage.CANCELED;
else return "";
}
public bool isPlayable()
{
return (!_played
&& !_multicard
&& !_canceled
&& _game.getGameStarted());
}
public void setTargetPlayer(int position)
{
switch (position)
{
case Game_classes.Player.NORD:
targetPlayer = _game.playerN;
break;
case Game_classes.Player.SUD:
targetPlayer = _game.playerS;
break;
case Game_classes.Player.EST:
targetPlayer = _game.playerE;
break;
case Game_classes.Player.OUEST:
targetPlayer = _game.playerO;
break;
}
}
public void newTag() {
if (_isGhost) nbGhosts++;
else nbCards++;
}
public void loseTag() {
if (_isGhost) nbGhosts--;
else nbCards--;
}
public bool playerExists(int pos)
{
return _game.getPlayer(pos) != null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.Carte_classes.Addons;
using ChtemeleSurfaceApplication.Carte_classes.Attaques;
using ChtemeleSurfaceApplication.Carte_classes;
using ChtemeleSurfaceApplication.HTML_classes;
namespace ChtemeleSurfaceApplication.Fabriques
{
class FabriqueCarte
{
/*---- Cartes Addons ----*/
//Antivirus
public static Antivirus CreateAntivirus()
{
return new Antivirus();
}
//BrowserUpdate
public static BrowserUpdate CreateBrowserUpdate()
{
return new BrowserUpdate();
}
//Cafe
public static Cafe CreateCafe()
{
return new Cafe();
}
//CodeInspector
public static CodeInspector CreateCodeInspector()
{
return new CodeInspector();
}
//CtrlF5
public static CtrlF5 CreateCtrlF5()
{
return new CtrlF5();
}
/*---- Cartes Attaques ----*/
//CrashBrowser
public static CrashBrowser CreateCrashBrowser()
{
return new CrashBrowser();
}
//Error303
public static Error303 CreateError303()
{
return new Error303();
}
//Error403
public static Error403 CreateError403()
{
return new Error403();
}
//Error404
public static Error404 CreateError404()
{
return new Error404();
}
//Freeze
public static Freeze CreateFreeze()
{
return new Freeze();
}
//ManInTheMiddle
public static ManInTheMiddle CreateManInTheMiddle()
{
return new ManInTheMiddle();
}
/*---- Cartes HTML ----*/
//Balises ouvrante
public static HTMLTagCarte CreateOpenH1()
{
return new HTMLTagCarte("h1", HtmlTag.HTMLTagType.OPENTAG, 2, true);
}
public static HTMLTagCarte CreateOpenH2()
{
return new HTMLTagCarte("h2", HtmlTag.HTMLTagType.OPENTAG, 2, true);
}
public static HTMLTagCarte CreateOpenP()
{
return new HTMLTagCarte("p", HtmlTag.HTMLTagType.OPENTAG, 2, true);
}
public static HTMLTagCarte CreateOpenDIV()
{
return new HTMLTagCarte("div", HtmlTag.HTMLTagType.OPENTAG, 2, true);
}
public static HTMLTagCarte CreateOpenBLOCKQUOTE()
{
return new HTMLTagCarte("blockquote", HtmlTag.HTMLTagType.OPENTAG, 2, true);
}
public static HTMLTagCarte CreateOpenHEADER()
{
return new HTMLTagCarte("header", HtmlTag.HTMLTagType.OPENTAG, 4, true);
}
public static HTMLTagCarte CreateOpenFOOTER()
{
return new HTMLTagCarte("footer", HtmlTag.HTMLTagType.OPENTAG, 4, true);
}
public static HTMLTagCarte CreateOpenASIDE()
{
return new HTMLTagCarte("aside", HtmlTag.HTMLTagType.OPENTAG, 4, true);
}
public static HTMLTagCarte CreateOpenSTRONG()
{
return new HTMLTagCarte("strong", HtmlTag.HTMLTagType.OPENTAG, 6, true);
}
public static HTMLTagCarte CreateOpenEM()
{
return new HTMLTagCarte("em", HtmlTag.HTMLTagType.OPENTAG, 6, true);
}
public static HTMLTagCarte CreateOpenA()
{
return new HTMLTagCarte("a", HtmlTag.HTMLTagType.OPENTAG, 8, true);
}
//Balises fermante
public static HTMLTagCarte CreateEndH1()
{
return new HTMLTagCarte("h1", HtmlTag.HTMLTagType.ENDTAG, 2, false);
}
public static HTMLTagCarte CreateEndH2()
{
return new HTMLTagCarte("h2", HtmlTag.HTMLTagType.ENDTAG, 2, false);
}
public static HTMLTagCarte CreateEndP()
{
return new HTMLTagCarte("p", HtmlTag.HTMLTagType.ENDTAG, 2, false);
}
public static HTMLTagCarte CreateEndDIV()
{
return new HTMLTagCarte("div", HtmlTag.HTMLTagType.ENDTAG, 2, false);
}
public static HTMLTagCarte CreateEndBLOCKQUOTE()
{
return new HTMLTagCarte("blockquote", HtmlTag.HTMLTagType.ENDTAG, 2, false);
}
public static HTMLTagCarte CreateEndHEADER()
{
return new HTMLTagCarte("header", HtmlTag.HTMLTagType.ENDTAG, 4, false);
}
public static HTMLTagCarte CreateEndFOOTER()
{
return new HTMLTagCarte("footer", HtmlTag.HTMLTagType.ENDTAG, 4, false);
}
public static HTMLTagCarte CreateEndASIDE()
{
return new HTMLTagCarte("aside", HtmlTag.HTMLTagType.ENDTAG, 4, false);
}
public static HTMLTagCarte CreateEndSTRONG()
{
return new HTMLTagCarte("strong", HtmlTag.HTMLTagType.ENDTAG, 6, false);
}
public static HTMLTagCarte CreateEndEM()
{
return new HTMLTagCarte("em", HtmlTag.HTMLTagType.ENDTAG, 6, false);
}
public static HTMLTagCarte CreateEndA()
{
return new HTMLTagCarte("a", HtmlTag.HTMLTagType.ENDTAG, 8, false);
}
//Balises simples
public static HTMLTagCarte CreateBR()
{
return new HTMLTagCarte("br", HtmlTag.HTMLTagType.OPENTAG, 4, false);
}
public static HTMLTagCarte CreateHR()
{
return new HTMLTagCarte("hr", HtmlTag.HTMLTagType.OPENTAG, 6, false);
}
public static HTMLTagCarte CreateIMG()
{
return new HTMLTagCarte("img", HtmlTag.HTMLTagType.OPENTAG, 8, false);
}
/*---- Cartes Attributs ----*/
// Href pour <a>
public static HTMLAttributeCarte CreateHREF()
{
return new HTMLAttributeCarte("href", "", 8);
}
// Src pour <img>
public static HTMLAttributeCarte CreateSRC()
{
return new HTMLAttributeCarte("src", "", 8);
}
// alt pour <img>
public static HTMLAttributeCarte CreateALT()
{
return new HTMLAttributeCarte("alt", "", 8);
}
// class
public static HTMLAttributeCarte CreateCLASS()
{
return new HTMLAttributeCarte("class", "", 4);
}
// id
public static HTMLAttributeCarte CreateID()
{
return new HTMLAttributeCarte("id", "", 4);
}
// style
public static HTMLAttributeCarte CreateSTYLE()
{
return new HTMLAttributeCarte("style", "", 4);
}
// title
public static HTMLAttributeCarte CreateTITLE()
{
return new HTMLAttributeCarte("title", "", 4);
}
}
}
<file_sep>using System.Windows;
using Microsoft.Surface.Presentation.Controls;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using ChtemeleSurfaceApplication.Carte_classes.Addons;
using ChtemeleSurfaceApplication.Carte_classes.Attaques;
using ChtemeleSurfaceApplication.Carte_classes;
using ChtemeleSurfaceApplication.Modeles;
using System.Media;
namespace ChtemeleSurfaceApplication
{
/// <summary>
/// Logique d'interaction pour Tag.xaml
/// </summary>
public partial class Tag : TagVisualization
{
// Constantes, enumérations ======================================================================================================
private static Dictionary<int, MdlTag> _mdls = new Dictionary<int,MdlTag>();
private static Dictionary<int, Tag> _views = new Dictionary<int, Tag>();
private static int lastIDInsert = 0;
private static Tag antivirus = null;
// Variables membres ======================================================================================================
private MdlTag _mdl = null;
private int _id;
// Constructeurs ======================================================================================================
public Tag()
{
InitializeComponent();
//On masque par défaut tous les éléments du TagVisualiseur
Message.Visibility = System.Windows.Visibility.Hidden;
Message.IsEnabled = false;
MenuDefault.Visibility = System.Windows.Visibility.Hidden;
MenuDefault.IsEnabled = false;
MenuAttaque.Visibility = System.Windows.Visibility.Hidden;
MenuAttaque.IsEnabled = false;
TextSelector.Visibility = System.Windows.Visibility.Hidden;
TextSelector.IsEnabled = false;
ImageSelector.Visibility = System.Windows.Visibility.Hidden;
ImageSelector.IsEnabled = false;
}
// Evénements ======================================================================================================
private void valider(object sender, RoutedEventArgs e)
{
//On saisit les informatiosn entrées dans le modèle
if (_mdl.hasTextEdit()) _mdl.textContent = TextSelector.Text;
//if (_mdl.hasImageSelector()) _mdl.textContent = ImageSelector.Text;
//On valide la carte
bool success = _mdl.validerCarte();
updateAll();
//Update du jeu
SurfaceWindow1.getInstance.updateCodeView();
SurfaceWindow1.getInstance.updateZonesJoueur();
showIndicators();
//Bruitage
if (success)
Sounder.playCardSound(_mdl.card);
else
Sounder.playSound(Sounder.FX_ERROR);
}
private void validerNord(object sender, RoutedEventArgs e) { if (_mdl.hasPlayerSelector()) _mdl.setTargetPlayer(Game_classes.Player.NORD); valider(sender, e); }
private void validerSud(object sender, RoutedEventArgs e) { if (_mdl.hasPlayerSelector()) _mdl.setTargetPlayer(Game_classes.Player.SUD); valider(sender, e); }
private void validerEst(object sender, RoutedEventArgs e) { if (_mdl.hasPlayerSelector()) _mdl.setTargetPlayer(Game_classes.Player.EST); valider(sender, e); }
private void validerOuest(object sender, RoutedEventArgs e) { if (_mdl.hasPlayerSelector()) _mdl.setTargetPlayer(Game_classes.Player.OUEST); valider(sender, e); }
private void gotTag(object sender, RoutedEventArgs e)
{
//On a récupéré un tag sur la table, on créée un MdlTag
++lastIDInsert;
_id = lastIDInsert;
_mdl = new MdlTag((int)VisualizedTag.Value);
_mdls.Add(lastIDInsert, _mdl);
_views.Add(lastIDInsert, this);
_mdl.onTag();
//Si on a un antivirus, on le stocke
if (_mdl.tag == (int)MdlTag.TagCorrespondance.ANTIVIRUS)
antivirus = this;
//On vérifie les catalyses (si des cartes s'activent automatiquement)
catalyse();
// Affichage du bon Layout
updateAll();
// Bruitage
if (!_mdl.isPlayable())
Sounder.playSound(Sounder.FX_ERROR);
else
Sounder.playSound(Sounder.FX_TAGOK);
}
private void lostTag(object sender, RoutedEventArgs e)
{
_mdl.onRemoved();
_mdls.Remove(_id);
_views.Remove(_id);
_mdl = null;
updateAll();
}
// Fonctionnalités ======================================================================================================
private void layoutMenu()
{
if (_mdl.hasPlayerSelector()) // MenuAttaque
{
// Il ne faut afficher que les joueurs présents dans la partie
// Nord
if (_mdl.playerExists(Game_classes.Player.NORD))
{
MA_PlayerNord.Header = SurfaceWindow1.getInstance.getMdl.getPlayerAt(Game_classes.Player.NORD).name;
MA_PlayerNord.Visibility = System.Windows.Visibility.Visible;
MA_PlayerNord.IsEnabled = true;
}
else
{
MA_PlayerNord.Visibility = System.Windows.Visibility.Collapsed;
MA_PlayerNord.IsEnabled = false;
}
//Est
if (_mdl.playerExists(Game_classes.Player.EST))
{
MA_PlayerEst.Header = SurfaceWindow1.getInstance.getMdl.getPlayerAt(Game_classes.Player.EST).name;
MA_PlayerEst.Visibility = System.Windows.Visibility.Visible;
MA_PlayerEst.IsEnabled = true;
}
else
{
MA_PlayerEst.Visibility = System.Windows.Visibility.Collapsed;
MA_PlayerEst.IsEnabled = false;
}
//Ouest
if (_mdl.playerExists(Game_classes.Player.OUEST))
{
MA_PlayerOuest.Header = SurfaceWindow1.getInstance.getMdl.getPlayerAt(Game_classes.Player.OUEST).name;
MA_PlayerOuest.Visibility = System.Windows.Visibility.Visible;
MA_PlayerOuest.IsEnabled = true;
}
else
{
MA_PlayerOuest.Visibility = System.Windows.Visibility.Collapsed;
MA_PlayerOuest.IsEnabled = false;
}
}
else // MenuDefault
{
// Rien à changer
}
}
private void catalyse()
{
foreach (KeyValuePair<int, MdlTag> mdl in _mdls)
{
if (!mdl.Value.isPlayable()) continue;
// CAS 1 : Antivirus + Attaque quelconque
if (antivirus != null && mdl.Value.typeCard == Carte.TypeCarte.ATTACK_CARD && antivirus._mdl.isPlayable())
{
antivirus._mdl.validerCarte();
mdl.Value.canceled = true;
}
}
}
private void showIndicators(){
string currentPlayerIndicator = "";
string targetPlayerIndicator = "";
switch (_mdl.tag)
{
case (int)MdlTag.TagCorrespondance.ANTIVIRUS: break;
case (int)MdlTag.TagCorrespondance.BROWSER_UPDATE: break;
case (int)MdlTag.TagCorrespondance.CAFE:
currentPlayerIndicator = IndicatorMessages.CAFE_EFFECT; break;
case (int)MdlTag.TagCorrespondance.CODE_INSPECTOR:
currentPlayerIndicator = IndicatorMessages.CODE_INSPECTOR_EFFECT; break;
case (int)MdlTag.TagCorrespondance.CTRL_F5:
currentPlayerIndicator = IndicatorMessages.CTRL_F5_EFFECT; break;
case (int)MdlTag.TagCorrespondance.ERROR_303:
currentPlayerIndicator = string.Format(IndicatorMessages.ERROR303_EFFECT, _mdl.targetPlayer.name); break;
case (int)MdlTag.TagCorrespondance.ERROR_403:
currentPlayerIndicator = string.Format(IndicatorMessages.ERROR403_EFFECT, _mdl.targetPlayer.name); break;
case (int)MdlTag.TagCorrespondance.ERROR_404:
targetPlayerIndicator = string.Format(IndicatorMessages.ERROR404_EFFECT, _mdl.targetPlayer.lastCombo().score.ToString()); break;
case (int)MdlTag.TagCorrespondance.MAN_IN_THE_MIDDLE:
currentPlayerIndicator = string.Format(IndicatorMessages.MAN_IN_THE_MIDDLE_EFFECT, _mdl.targetPlayer.name); break;
default: break;
}
if (currentPlayerIndicator.Length != 0)
SurfaceWindow1.getInstance.indicatorCurrentPlayer(currentPlayerIndicator);
if (targetPlayerIndicator.Length != 0)
SurfaceWindow1.getInstance.indicatorAt(targetPlayerIndicator, _mdl.targetPlayer);
}
// Update ======================================================================================================
private static void updateAll()
{
foreach (KeyValuePair<int, MdlTag> mdl in _mdls)
{
mdl.Value.computeMulticard();
}
foreach (KeyValuePair<int, Tag> view in _views)
{
view.Value.Message.Text = view.Value._mdl.getInfoMessage();
view.Value.Message.Visibility = (view.Value.Message.Text == "") ? System.Windows.Visibility.Hidden : System.Windows.Visibility.Visible;
if (view.Value._mdl.isPlayable())
{
if (view.Value._mdl.hasTextEdit()) // inputBox
{
view.Value.TextSelector.Visibility = (view.Value._mdl.isPlayable()) ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden;
view.Value.TextSelector.IsEnabled = view.Value._mdl.isPlayable();
}
if (view.Value._mdl.hasPlayerSelector()) // MenuAttaque
{
view.Value.MenuAttaque.Visibility = (view.Value._mdl.isPlayable()) ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden;
view.Value.MenuAttaque.IsEnabled = view.Value._mdl.isPlayable();
view.Value.MenuDefault.Visibility = System.Windows.Visibility.Hidden;
view.Value.MenuDefault.IsEnabled = false;
}
else // MenuDefault
{
view.Value.MenuDefault.Visibility = (view.Value._mdl.isPlayable()) ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden;
view.Value.MenuDefault.IsEnabled = view.Value._mdl.isPlayable();
view.Value.MenuAttaque.Visibility = System.Windows.Visibility.Hidden;
view.Value.MenuAttaque.IsEnabled = false;
}
if (view.Value._mdl.hasImageSelector()) // imageSelector
{
view.Value.ImageSelector.Visibility = (view.Value._mdl.isPlayable()) ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden;
view.Value.ImageSelector.IsEnabled = view.Value._mdl.isPlayable();
view.Value.TextSelector.Visibility = System.Windows.Visibility.Hidden;
string imagesPath = System.IO.Directory.GetCurrentDirectory();
imagesPath = imagesPath + "\\Resources\\Image\\";
try
{
string[] files = System.IO.Directory.GetFiles(imagesPath, "*.jpg");
ObservableCollection<string> items = new ObservableCollection<string>();
Collection<string> names = new Collection<string>();
foreach (string file in files)
{
items.Add(file);
}
view.Value.ImageSelector.ItemsSource = items;
}
catch (System.IO.DirectoryNotFoundException) { }
}
view.Value.layoutMenu();
}
else
{
view.Value.MenuDefault.Visibility = System.Windows.Visibility.Hidden;
view.Value.MenuDefault.IsEnabled = false;
view.Value.MenuAttaque.Visibility = System.Windows.Visibility.Hidden;
view.Value.MenuAttaque.IsEnabled = false;
view.Value.TextSelector.Visibility = System.Windows.Visibility.Hidden;
view.Value.TextSelector.IsEnabled = false;
view.Value.ImageSelector.Visibility = System.Windows.Visibility.Hidden;
view.Value.ImageSelector.IsEnabled = false;
}
}
}
private void img_Click(object sender, RoutedEventArgs e)
{
SurfaceButton btn = e.Source as SurfaceButton;
string imagesPath = System.IO.Directory.GetCurrentDirectory();
//On recupère le nom de l'image
string imgName = (btn.Content as Image).Source.ToString();
bool find = false;
int length = 0;
for (int i = imgName.Length-1; i > 0 && find != true; i--)
{
if (imgName[i] == '/')
{
find = true;
length = i+1;
}
}
imgName = imgName.Substring(length);
TextSelector.Text = "Resources/Documentation/img/" + imgName;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.HTML_classes;
namespace ChtemeleSurfaceApplication.Game_classes
{
public class Game
{
// Constantes, enumérations ======================================================================================================
public static int DEFAULT_HAND_SIZE = 10;
public static int DEFAULT_NB_STEPS = 10;
//Singleton
private static Game instance = null;
public static Game getInstance{
get{
if (instance == null)
instance = new Game();
return instance;
}
}
// Variables membres ======================================================================================================
private Player _joueurS, _joueurN, _joueurE, _joueurO; //les 4 joueurs
private int _nbPlayer; //Nombre de joueur
private int _step; // numéro du tour actuel
private int _subStep;
private int _nbSteps; // nombre de tours de la partie
private Player _currentPlayer; // joueur actif
private bool gameStarted;
private bool _isThereAntivirus = false; // Y'a-t-il un antivirus sur la table ?
private HtmlPage _page; // page HTML de la partie
//Position des navigateurs sur la table
public Dictionary<int, int> LocationNav;
// Constructeurs ======================================================================================================
protected Game()
{
_joueurS = null;
_joueurN = null;
_joueurE = null;
_joueurO = null;
_step = 0;
_subStep = 0;
_nbSteps = Game.DEFAULT_NB_STEPS;
_currentPlayer = null;
gameStarted = false;
_page = new HtmlPage();
LocationNav = new Dictionary<int, int>
{
{Player.FIREFOX, Player.OUT},
{Player.CHROME, Player.OUT},
{Player.IE, Player.OUT},
{Player.SAFARI, Player.OUT},
{Player.OPERA, Player.OUT}
};
}
// Accesseurs / Mutateurs ======================================================================================================
public HtmlPage getPage() { return _page; }
public bool getGameStarted() { return gameStarted; }
public Player getCurPlayer() { return _currentPlayer; }
public int getCurrentStep() { return _step; }
public int getTotalSteps() { return _nbSteps; }
public bool isThereAntivirus { get { return _isThereAntivirus; } set { _isThereAntivirus = value; } }
public Player playerS { get { return _joueurS; } }
public Player playerO { get { return _joueurO; } }
public Player playerN { get { return _joueurN; } }
public Player playerE { get { return _joueurE; } }
// Fonctionnalités ======================================================================================================
/// <summary>
/// Setter du joeur à la position spécifiée.
/// </summary>
/// <param name="p">Nouvelle valeur</param>
/// <param name="position">Player.NORD|SUD|EST|OUEST</param>
public void setPlayer(Player p, int position)
{
switch (position)
{
case Player.SUD: _joueurS = p; break;
case Player.OUEST: _joueurO = p; break;
case Player.NORD: _joueurN = p; break;
case Player.EST: _joueurE = p; break;
default: break;
}
}
/// <summary>
/// Setter du joeur à la position spécifiée.
/// </summary>
/// <param name="p">Nouvelle valeur</param>
/// <param name="position">Player.NORD|SUD|EST|OUEST</param>
public Player getPlayer(int position)
{
switch (position)
{
case Player.SUD: return _joueurS;
case Player.OUEST: return _joueurO;
case Player.NORD: return _joueurN;
case Player.EST: return _joueurE;
default: return null;
}
}
public void setNbPlayer(int nbPlayer)
{
_nbPlayer = nbPlayer;
}
public int getNbPlayer()
{
return _nbPlayer;
}
public void initGame()
{
// Step 1 : On choisit le joueur qui commence au hasard.
Random rand = new Random();
// Step 1.1 : On dresse une liste des joueurs disponibles
List<int> listePos = new List<int>();
if (_joueurS != null) listePos.Add(Player.SUD);
if (_joueurO != null) listePos.Add(Player.OUEST);
if (_joueurN != null) listePos.Add(Player.NORD);
if (_joueurE != null) listePos.Add(Player.EST);
// Step 1.2 : On choisit aléatoirement lequel de ces joueur sera celui qui commence
int numPlay = rand.Next(0, listePos.Count - 1);
_currentPlayer = getPlayer(listePos[numPlay]);
// Step 2 : On dit que le jeu a commencé.
gameStarted = true;
}
/// <summary>
/// Met dans currentPlayer le jour suivant en suivant le sens horaire.
/// </summary>
public void nextPlayer()
{
// Step 0 : On incrémente les valeurs des étapes, et on passe la fin
_subStep++;
if (_subStep >= _nbPlayer) _step++;
_subStep %= _nbPlayer;
if (_step >= _nbSteps) endGame();
// Step 1.1 : On dresse une liste des joueurs disponibles
int indexCurPlayer = 0;
bool found = false;
List<int> listePos = new List<int>();
if (_joueurS != null){
listePos.Add(Player.SUD);
if (_currentPlayer != _joueurS) //c'est le 1ere test, on sait que found = false, forcément, pas besoin de tester.
indexCurPlayer++;
else
found = true;
}
if (_joueurO != null)
{
listePos.Add(Player.OUEST);
if (_currentPlayer != _joueurO && !found)
indexCurPlayer++;
else
found = true;
}
if (_joueurN != null)
{
listePos.Add(Player.NORD);
if (_currentPlayer != _joueurN && !found)
indexCurPlayer++;
else
found = true;
}
if (_joueurE != null)
{
listePos.Add(Player.EST);
if (_currentPlayer != _joueurE && !found)
indexCurPlayer++;
else
found = true;
}
indexCurPlayer++;
indexCurPlayer %= _nbPlayer;
_currentPlayer = getPlayer(listePos[indexCurPlayer]);
// On a le joueur suivant, on reset sa dernière combo
_currentPlayer.lastCombo().reset();
}
public void endGame()
{
// Fin de partie
gameStarted = false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.Carte_classes.Attaques
{
public class Error404 : AttaqueCarte
{
public Error404() : base() { }
public override void onValid()
{
target.addPoint(-target.lastCombo().score);
}
public override void onPlay() { }
public override void onDelete() { }
}
}
<file_sep>using System;
using System.IO;
//using System.Windows.Shapes.Path;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
//using System.Windows.Shapes;
using ChtemeleSurfaceApplication.HTML_classes;
using ChtemeleSurfaceApplication.Game_classes;
using ChtemeleSurfaceApplication.Modeles;
using Microsoft.Surface.Presentation.Controls;
namespace ChtemeleSurfaceApplication
{
/// <summary>
/// Logique d'interaction pour PageCode.xaml
/// </summary>
public partial class PageCode : ScatterViewItem
{
// Constantes, enumérations ======================================================================================================
/*private Dictionary<StrTypePair.StrType, Color> colorTable = new Dictionary<StrTypePair.StrType, Color>
{
{StrTypePair.StrType.DOCTYPE, Colors.BlueViolet},
{StrTypePair.StrType.USR_TAG, Color.FromRgb(0, 0, 127)},
{StrTypePair.StrType.USR_TAG_ATTR_NAME, Color.FromRgb(255, 0, 0)},
{StrTypePair.StrType.USR_TAG_ATTR_AFFECT, Color.FromRgb(0, 0, 0)},
{StrTypePair.StrType.USR_TAG_ATTR_VALUE, Color.FromRgb(128, 0, 255)},
{StrTypePair.StrType.USR_TEXT, Color.FromRgb(0, 0, 0)},
{StrTypePair.StrType.USR_TAG, Color.FromRgb(127, 127, 255)},
{StrTypePair.StrType.USR_TAG_ATTR_NAME, Color.FromRgb(255, 127, 127)},
{StrTypePair.StrType.USR_TAG_ATTR_AFFECT, Color.FromRgb(127, 127, 127)},
{StrTypePair.StrType.USR_TAG_ATTR_VALUE, Color.FromRgb(180, 127, 255)},
{StrTypePair.StrType.USR_TEXT, Color.FromRgb(127, 127, 127)},
{StrTypePair.StrType.COMMENT, Color.FromRgb(0, 127, 0)},
{StrTypePair.StrType.LINE_BREAK, Color.FromRgb(0, 0, 0)}
};*/
private Dictionary<StrTypePair.StrType, Color> colorTable = new Dictionary<StrTypePair.StrType, Color>
{
{StrTypePair.StrType.DOCTYPE, Colors.SaddleBrown},
{StrTypePair.StrType.USR_TAG, Colors.Blue},
{StrTypePair.StrType.USR_OPEN_TAG, Colors.Blue},
{StrTypePair.StrType.USR_END_TAG, Colors.Blue},
{StrTypePair.StrType.USR_TAG_NAME, Colors.Blue},
{StrTypePair.StrType.USR_TAG_ATTR_NAME, Colors.Red},
{StrTypePair.StrType.USR_TAG_ATTR_AFFECT, Colors.Black },
{StrTypePair.StrType.USR_TAG_ATTR_VALUE, Colors.Purple},
{StrTypePair.StrType.USR_TEXT, Colors.Black},
{StrTypePair.StrType.AUTO_TAG, Colors.LightSlateGray},
{StrTypePair.StrType.AUTO_OPEN_TAG, Colors.LightSlateGray},
{StrTypePair.StrType.AUTO_END_TAG, Colors.LightSlateGray},
{StrTypePair.StrType.AUTO_TAG_NAME, Colors.LightSlateGray},
{StrTypePair.StrType.AUTO_TAG_ATTR_NAME, Colors.Tomato},
{StrTypePair.StrType.AUTO_TAG_ATTR_AFFECT, Colors.Gray},
{StrTypePair.StrType.AUTO_TAG_ATTR_VALUE, Colors.Plum},
{StrTypePair.StrType.AUTO_TEXT, Colors.Gray},
{StrTypePair.StrType.COMMENT, Colors.Green},
{StrTypePair.StrType.LINE_BREAK, Colors.Black}
};
// Variables membres ======================================================================================================
private string _text; // texte html à afficher
private MdlPageCode _mdl; // Modèle
// Constructeurs ======================================================================================================
public PageCode()
{
InitializeComponent();
Width = ScatterCodeText.Width;
Height = ScatterCodeText.Height;
}
private void PageCode_Loaded(object sender, RoutedEventArgs e)
{
_mdl = SurfaceWindow1.getInstance.getMdl.mPageCode;
// URL du fichier local à lire (ne fonctionne pas avec les URLs distantes)
//string temp = System.IO.Directory.GetCurrentDirectory();
//temp = temp + "/Resources/Savegame/game_0.html";
//string temp = System.IO.Path.GetFullPath("./Resources/Savegame/game_0.html");
ShowCode();
}
// Fonctionnalités ======================================================================================================
// Retourne les lignes récupéré par le set
public string getTextCode()
{
return _text;
}
// Lis un fichier et enregistre chaque ligne
public void setTextCode(string txt)
{
_text = txt;
}
// Affiche le texte
public void ShowCode()
{
_mdl.renderPage();
CodeText.Inlines.Clear();
foreach (StrTypePair pair in _mdl.getCode())
{
Run txt = new Run(pair.str);
txt.Foreground = new SolidColorBrush(colorTable[pair.type]);
CodeText.Inlines.Add(txt);
}
//CodeText.Inlines.Add(new Run(_mdl.getCode()));
}
public void saveHTML(string filepath)
{
_mdl.saveHTML(filepath);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*
*
* Au prochain tour, le joueur ciblé ne piochera que jusqu’à avoir 4 cartes de moins. (6 au lieu de 10, 8 au lieu de 12.)
*
* */
// include
using ChtemeleSurfaceApplication.Game_classes;
namespace ChtemeleSurfaceApplication.Effect_classes
{
class CrashBrowser : Effect
{
public Player player;
// Constructeur
public CrashBrowser()
: base()
{
_type = EffectType.CRASHBROWSER;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Surface;
using Microsoft.Surface.Presentation;
using Microsoft.Surface.Presentation.Controls;
using Microsoft.Surface.Presentation.Input;
using ChtemeleSurfaceApplication.Modeles;
using ChtemeleSurfaceApplication.Game_classes;
using System.Media;
namespace ChtemeleSurfaceApplication
{
/// <summary>
/// Interaction logic for SurfaceWindow1.xaml
/// </summary>
public partial class SurfaceWindow1 : SurfaceWindow
{
// Constantes, enumérations ======================================================================================================
public static SurfaceWindow1 instance = null; //Singleton
public static SurfaceWindow1 getInstance{get{return instance;}}
public MdlGame getMdl { get { return _mdl; } }
// Variables membres ======================================================================================================
private MdlGame _mdl;
//private Game _game; // Référence vers le jeu
public static Dictionary<int, CartesJoueurs> tabCartes; // Tableau des cartes Joueurs localisées
// Constructeurs ======================================================================================================
/// <summary>
/// Default constructor.
/// </summary>
public SurfaceWindow1()
{
InitializeComponent();
instance = this;
tabCartes = new Dictionary<int, CartesJoueurs>
{
{Player.SUD, ZoneJoueurS.CarteJoueur},
{Player.EST, ZoneJoueurE.CarteJoueur},
{Player.NORD, ZoneJoueurN.CarteJoueur},
{Player.OUEST, ZoneJoueurO.CarteJoueur}
};
// Position des cartes joueurs
ZoneJoueurN.CarteJoueur.position = Player.NORD;
ZoneJoueurS.CarteJoueur.position = Player.SUD;
ZoneJoueurE.CarteJoueur.position = Player.EST;
ZoneJoueurO.CarteJoueur.position = Player.OUEST;
// Add handlers for window availability events
AddWindowAvailabilityHandlers();
ComputeWidgetsPositions(MainScatterView.Width, MainScatterView.Height);
}
private void SurfaceWindow_Loaded(object sender, RoutedEventArgs e)
{
_mdl = new MdlGame();
updateStepIndicator();
}
// Accesseurs & Mutateurs ======================================================================================================
public ZoneJoueur getCurrentPlayerZone()
{
switch (_mdl.getCurrentPlayer().position())
{
case Player.SUD: return SurfaceWindow1.getInstance.ZoneJoueurS;
case Player.OUEST: return SurfaceWindow1.getInstance.ZoneJoueurO;
case Player.NORD: return SurfaceWindow1.getInstance.ZoneJoueurN;
case Player.EST: return SurfaceWindow1.getInstance.ZoneJoueurE;
default: return null;
}
}
// Evénements ======================================================================================================
/// <summary>
/// Occurs when the window is about to close.
/// </summary>
/// <param name="e"></param>
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// Remove handlers for window availability events
RemoveWindowAvailabilityHandlers();
}
/// <summary>
/// Adds handlers for window availability events.
/// </summary>
private void AddWindowAvailabilityHandlers()
{
// Subscribe to surface window availability events
ApplicationServices.WindowInteractive += OnWindowInteractive;
ApplicationServices.WindowNoninteractive += OnWindowNoninteractive;
ApplicationServices.WindowUnavailable += OnWindowUnavailable;
}
/// <summary>
/// Removes handlers for window availability events.
/// </summary>
private void RemoveWindowAvailabilityHandlers()
{
// Unsubscribe from surface window availability events
ApplicationServices.WindowInteractive -= OnWindowInteractive;
ApplicationServices.WindowNoninteractive -= OnWindowNoninteractive;
ApplicationServices.WindowUnavailable -= OnWindowUnavailable;
}
/// <summary>
/// This is called when the user can interact with the application's window.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnWindowInteractive(object sender, EventArgs e)
{
//TODO: enable audio, animations here
}
/// <summary>
/// This is called when the user can see but not interact with the application's window.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnWindowNoninteractive(object sender, EventArgs e)
{
//TODO: Disable audio here if it is enabled
//TODO: optionally enable animations here
}
/// <summary>
/// This is called when the application's window is not visible or interactive.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnWindowUnavailable(object sender, EventArgs e)
{
//TODO: disable audio, animations here
}
/// <summary>
/// Re-dessine la fenêtre, repositionne les éléments
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainScatterView_SizeChanged(object sender, SizeChangedEventArgs e)
{
ComputeWidgetsPositions(e.NewSize.Width, e.NewSize.Height);
}
public void rotateCenterView(int pos)
{
switch(pos)
{
case Player.SUD:
CenterView.Orientation = 0;
PageCode.Orientation = 0;
PageRendu.Orientation = 0;
break;
case Player.OUEST:
CenterView.Orientation = 0;
PageCode.Orientation = 90;
PageRendu.Orientation = 90;
break;
case Player.NORD:
CenterView.Orientation = 180;
PageCode.Orientation = 0;
PageRendu.Orientation = 0;
break;
case Player.EST:
CenterView.Orientation = 180;
PageCode.Orientation = 90;
PageRendu.Orientation = 90;
break;
default: break;
}
}
private void twoPlayer(object sender, RoutedEventArgs e)
{
_mdl.setNbPlayer(2);
initGrid.Visibility = System.Windows.Visibility.Hidden;
playGrid.Visibility = System.Windows.Visibility.Visible;
}
private void threePlayer(object sender, RoutedEventArgs e)
{
_mdl.setNbPlayer(3);
initGrid.Visibility = System.Windows.Visibility.Hidden;
playGrid.Visibility = System.Windows.Visibility.Visible;
}
private void fourPlayer(object sender, RoutedEventArgs e)
{
_mdl.setNbPlayer(4);
initGrid.Visibility = System.Windows.Visibility.Hidden;
playGrid.Visibility = System.Windows.Visibility.Visible;
}
protected void OnPreviewTouchDown(object sender, TouchEventArgs e)
{
bool isFinger = e.TouchDevice.GetIsFingerRecognized();
bool isTag = e.TouchDevice.GetIsTagRecognized();
if (isFinger == false && isTag == false)
{
e.Handled = true;
}
}
// Fonctionnalités ======================================================================================================
private void ComputeWidgetsPositions(double x, double y)
{
//Position des zones joueurs
ZoneJoueurS.Center = new Point((x / 2) - 20, y - (ZoneJoueurS.Height / 2));
ZoneJoueurO.Center = new Point(ZoneJoueurO.Height / 2, (y / 2) - 20);
ZoneJoueurN.Center = new Point((x / 2) + 20, ZoneJoueurN.Height / 2);
ZoneJoueurE.Center = new Point(x - ZoneJoueurE.Height / 2, (y / 2) + 20);
//taille et position du centralview
CenterView.Height = y - ZoneJoueurS.Height - ZoneJoueurN.Height;
CenterView.Width = x - ZoneJoueurO.Height - ZoneJoueurE.Height;
CenterView.Center = new Point(x / 2.0, y / 2.0);
// Taille du scatter contenant les deux rendus + la zone de pioche
ScatterCenterView.Height = CenterView.Height;
ScatterCenterView.Width = CenterView.Width;
// Emplacement selon rotation des élements des rendus
if ((CenterView.Orientation == 0 && PageCode.Orientation == 90) || (PageCode.Orientation == 180 && PageCode.Orientation == 90))
{
ZonePioche.Width = ScatterCenterView.Width - PageCode.Width - PageRendu.Width;
ZonePioche.Height = ScatterCenterView.Height;
PageCode.Height = ScatterCenterView.Height;
PageRendu.Height = ScatterCenterView.Height;
PageRendu.Height = ScatterCenterView.Height;
PageCode.Height = ScatterCenterView.Height;
ZonePioche.Width = ScatterCenterView.Width / 10;
PageCode.Width = (ScatterCenterView.Width - ZonePioche.Width) / 2.0;
PageRendu.Width = (ScatterCenterView.Width - ZonePioche.Width) / 2.0;
PageCode.Width = (ScatterCenterView.Width - ZonePioche.Width) / 2.0;
PageRendu.Width = (ScatterCenterView.Width - ZonePioche.Width) / 2.0;
}
if ((CenterView.Orientation == 0 && PageCode.Orientation == 0) || (PageCode.Orientation == 180 && PageCode.Orientation == 0))
{
ZonePioche.Height = ScatterCenterView.Height;
PageCode.Width = ScatterCenterView.Height;
PageRendu.Width = ScatterCenterView.Height;
PageRendu.Width = ScatterCenterView.Height;
PageCode.Width = ScatterCenterView.Height;
ZonePioche.Width = ScatterCenterView.Width - PageCode.Width - PageRendu.Width;
PageCode.Height = (ScatterCenterView.Width - ZonePioche.Width) / 2.0;
PageRendu.Height = (ScatterCenterView.Width - ZonePioche.Width) / 2.0;
PageCode.Height = (ScatterCenterView.Width - ZonePioche.Width) / 2.0;
PageRendu.Height = (ScatterCenterView.Width - ZonePioche.Width) / 2.0;
}
ZonePioche.Center = new Point(ScatterCenterView.Width / 2.0, ScatterCenterView.Height / 2.0);
PageCode.Center = new Point(PageCode.Width / 2.0, ScatterCenterView.Height / 2.0);
PageRendu.Center = new Point(ScatterCenterView.Width - PageRendu.Width / 2.0, ScatterCenterView.Height / 2.0);
//Zone de pioche/defausse/StepIndicator
ZonePiocheGrid.Width = ZonePioche.Width;
ZonePiocheGrid.Height = ZonePioche.Height;
}
public void layoutGameStarted()
{
//Supprime les zone de joueur inactive
if (_mdl.getPlayerAt(Player.SUD) == null)
ZoneJoueurS.Visibility = System.Windows.Visibility.Hidden;
if (_mdl.getPlayerAt(Player.EST) == null)
ZoneJoueurE.Visibility = System.Windows.Visibility.Hidden;
if (_mdl.getPlayerAt(Player.OUEST) == null)
ZoneJoueurO.Visibility = System.Windows.Visibility.Hidden;
if (_mdl.getPlayerAt(Player.NORD) == null)
ZoneJoueurN.Visibility = System.Windows.Visibility.Hidden;
switch (_mdl.getCurrentPlayer().position())
{
case Player.SUD: ZoneJoueurS.active = true; break;
case Player.OUEST: ZoneJoueurO.active = true; break;
case Player.NORD: ZoneJoueurN.active = true; break;
case Player.EST: ZoneJoueurE.active = true; break;
default: break;
}
rotateCenterView(_mdl.getCurrentPlayer().position());
updateZonesJoueur();
updateCodeView();
Sounder.playCurrentPlayerSound();
SurfaceWindow1.getInstance.indicatorCurrentPlayer(IndicatorMessages.YOUR_TURN);
}
public void indicatorAt(string text, Player p)
{
switch (p.position())
{
case Player.SUD: ZoneJoueurS.showIndicator(text); break;
case Player.OUEST: ZoneJoueurO.showIndicator(text); break;
case Player.NORD: ZoneJoueurN.showIndicator(text); break;
case Player.EST: ZoneJoueurE.showIndicator(text); break;
default: break;
}
}
public void indicatorCurrentPlayer(string text)
{
indicatorAt(text, _mdl.getCurrentPlayer());
}
// Update ======================================================================================================
public void updateCodeView()
{
PageCode.saveHTML(_mdl.htmlFilePath);
PageCode.ShowCode();
PageRendu.update();
}
public void updateRotation()
{
rotateCenterView(_mdl.getCurrentPlayer().position());
}
public void updateStepIndicator()
{
StepIndicator.Text = _mdl.getCurrentStep().ToString() + '/' + _mdl.getTotalStep().ToString();
}
public void updateZonesJoueur()
{
// SUD
if (_mdl.getPlayerAt(Player.SUD) != null)
{
ZoneJoueurS.active = (_mdl.getCurrentPlayer() == _mdl.getPlayerAt(Player.SUD));
ZoneJoueurS.Visibility = System.Windows.Visibility.Visible;
ZoneJoueurS.IsEnabled = true;
ZoneJoueurS.update();
}
else
{
ZoneJoueurS.active = false;
ZoneJoueurS.Visibility = System.Windows.Visibility.Hidden;
ZoneJoueurS.IsEnabled = false;
}
// OUEST
if (_mdl.getPlayerAt(Player.OUEST) != null)
{
ZoneJoueurO.active = (_mdl.getCurrentPlayer() == _mdl.getPlayerAt(Player.OUEST));
ZoneJoueurO.Visibility = System.Windows.Visibility.Visible;
ZoneJoueurO.IsEnabled = true;
ZoneJoueurO.update();
}
else
{
ZoneJoueurO.active = false;
ZoneJoueurO.Visibility = System.Windows.Visibility.Hidden;
ZoneJoueurO.IsEnabled = false;
}
// NORD
if (_mdl.getPlayerAt(Player.NORD) != null)
{
ZoneJoueurN.active = (_mdl.getCurrentPlayer() == _mdl.getPlayerAt(Player.NORD));
ZoneJoueurN.Visibility = System.Windows.Visibility.Visible;
ZoneJoueurN.IsEnabled = true;
ZoneJoueurN.update();
}
else
{
ZoneJoueurN.active = false;
ZoneJoueurN.Visibility = System.Windows.Visibility.Hidden;
ZoneJoueurN.IsEnabled = false;
}
// EST
if (_mdl.getPlayerAt(Player.EST) != null)
{
ZoneJoueurE.active = (_mdl.getCurrentPlayer() == _mdl.getPlayerAt(Player.EST));
ZoneJoueurE.Visibility = System.Windows.Visibility.Visible;
ZoneJoueurE.IsEnabled = true;
ZoneJoueurE.update();
}
else
{
ZoneJoueurE.active = false;
ZoneJoueurE.Visibility = System.Windows.Visibility.Hidden;
ZoneJoueurE.IsEnabled = false;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*
*
* Au prochain tour vous piocherez jusqu’à avoir 2 cartes de plus. (12 au lieu de 10, 8 au lieu de 10.)
*
* */
// include
using ChtemeleSurfaceApplication.Game_classes;
namespace ChtemeleSurfaceApplication.Effect_classes
{
class BrowserUpdate : Effect
{
public Player player;
// Constructeur
public BrowserUpdate()
: base()
{
_type = EffectType.BROWSERUPDATE;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Media;
using ChtemeleSurfaceApplication.Game_classes;
using ChtemeleSurfaceApplication.Carte_classes;
namespace ChtemeleSurfaceApplication
{
public static class Sounder
{
// Constantes, enumérations ======================================================================================================
public const string soundDir = "Resources/";
public const string FX_FIREFOX = soundDir + "firefox.wav";
public const string FX_CHROME = soundDir + "chrome.wav";
public const string FX_OPERA = soundDir + "opera.wav";
public const string FX_SAFARI = soundDir + "safari.wav";
public const string FX_EXPLORER = soundDir + "explorer.wav";
public const string FX_BOOM = soundDir + "boom.wav";
public const string FX_POINTS = soundDir + "points.wav";
public const string FX_BONUS = soundDir + "bonus.wav";
public const string FX_MALUS = soundDir + "malus.wav";
public const string FX_OK = soundDir + "ok.wav";
public const string FX_ERROR = soundDir + "error.wav";
public const string FX_TAGOK = soundDir + "cymbal.wav";
// Variables membres ======================================================================================================
public static bool mute = false;
// Constructeurs ======================================================================================================
// Classe statique, on ne l'instancie pas.
// Accesseurs / Mutateurs ======================================================================================================
// Fonctionnalités ======================================================================================================
public static void playSound(string filename)
{
if (mute) return;
using (SoundPlayer player = new SoundPlayer(filename))
{
player.Play();
}
}
public static void playCurrentPlayerSound()
{
string snd;
switch (SurfaceWindow1.getInstance.getMdl.getCurrentPlayer().browser)
{
case Player.FIREFOX: snd = Sounder.FX_FIREFOX; break;
case Player.CHROME: snd = Sounder.FX_CHROME; break;
case Player.OPERA: snd = Sounder.FX_OPERA; break;
case Player.SAFARI: snd = Sounder.FX_SAFARI; break;
case Player.IE: snd = Sounder.FX_EXPLORER; break;
default: snd = Sounder.FX_BOOM; break;
}
Sounder.playSound(snd);
}
public static void playCardSound(Carte card)
{
if (card is HTMLTagCarte || card is HTMLAttributeCarte)
Sounder.playSound(Sounder.FX_POINTS);
else if (card is AttaqueCarte)
Sounder.playSound(Sounder.FX_MALUS);
else if (card is AddonCarte)
Sounder.playSound(Sounder.FX_BONUS);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.Game_classes
{
public class Effect
{
public enum EffectType
{
BROWSERUPDATE,
CRASHBROWSER,
FREEZE
};
protected EffectType _type;
public EffectType getTypeEffect() { return _type; }
// constructeur
public Effect()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ChtemeleSurfaceApplication.HTML_classes;
namespace ChtemeleSurfaceApplication.Modeles
{
public class StrTypePair{
public enum StrType // Toutes les sortes de chaines à styliser
{
DOCTYPE,
USR_TAG,
USR_OPEN_TAG,
USR_END_TAG,
USR_TAG_NAME,
USR_TAG_ATTR_NAME,
USR_TAG_ATTR_AFFECT,
USR_TAG_ATTR_VALUE,
USR_TEXT,
AUTO_TAG,
AUTO_OPEN_TAG,
AUTO_END_TAG,
AUTO_TAG_NAME,
AUTO_TAG_ATTR_NAME,
AUTO_TAG_ATTR_AFFECT,
AUTO_TAG_ATTR_VALUE,
AUTO_TEXT,
COMMENT,
LINE_BREAK
}
public string str = null;
public StrType type;
public StrTypePair(string s, StrType t) {
str = s;
type = t;
}
};
public class MdlPageCode : Modele
{
// Constantes, enumérations ======================================================================================================
public static List<string> _htmlAutoTags = new List<string>
{
"html", "head", "title", "body", "link", "meta"
};
// Variables membres ======================================================================================================
private HtmlPage _page; //Données du modèle
private List<StrTypePair> _code; //Code généré
private int _indentLevel;
private int indentSize = 4;
private StrTypePair _currentLineBreak;
private bool _isAutoTag = false;
// Constructeurs ======================================================================================================
public MdlPageCode()
: base()
{
_page = _game.getPage();
_code = new List<StrTypePair>();
_indentLevel = 0;
}
// Accesseurs / Mutateurs ======================================================================================================
public List<StrTypePair> getCode() { return _code; }
// Fonctionnalités ======================================================================================================
// Rendu d'une page HTML
public void renderPage()
{
_code.Clear();
_code.Add(new StrTypePair(_page.doctype(), StrTypePair.StrType.DOCTYPE));
_code.Add(new StrTypePair("\n", StrTypePair.StrType.LINE_BREAK));
_code.AddRange(renderHtmlElement(_page.mainTag()));
removeDoubleLineBreaks();
autoIndent();
}
// Rendu d'un élément HTML
public List<StrTypePair> renderHtmlElement(HtmlElement elem)
{
List<StrTypePair> res = new List<StrTypePair>();
//on détermine le type de balise
bool multiline = HtmlElement.multiLineTags.Exists(v => v == elem.getTagname());
bool monoline = HtmlElement.monoLineTags.Exists(v => v == elem.getTagname());
bool inline = (!multiline && !monoline);
_isAutoTag = _htmlAutoTags.Exists(v => v == elem.getTagname());
//chaine des attributs
List<StrTypePair> resattr = new List<StrTypePair>();
if (elem.attributes.Count > 0)
{
foreach (HtmlTagAttribute attr in elem.attributes)
{
resattr.Add(new StrTypePair(" ", (_isAutoTag) ? StrTypePair.StrType.AUTO_TAG : StrTypePair.StrType.USR_TAG));
resattr.AddRange(renderHtmlTagAttribute(attr));
}
}
//OpenTag
//if (multiline) res += '\n';
res.AddRange(renderHtmlTag(elem.getOpenTag(), resattr));
//retour à la ligne post-OpenTag multiline
if (multiline) res.Add(new StrTypePair("\n", StrTypePair.StrType.LINE_BREAK));
//content
if (elem.tagContent.Count > 0)
{
foreach (HtmlTagContent e in elem.tagContent)
{
if(e is HtmlElement)
res.AddRange(renderHtmlElement(e as HtmlElement));
else if(e is HtmlText)
res.Add(renderHtmlText(e as HtmlText));
}
}
//indentation avant les multilines (intent ='' pour les inlines)
if (multiline) res.Add(new StrTypePair("\n", StrTypePair.StrType.LINE_BREAK));
//EndTag
if (elem.isClosed())
res.AddRange(renderHtmlTag(elem.getEndTag()));
//retour à la ligne post-non-inline
if (!inline) res.Add(new StrTypePair("\n", StrTypePair.StrType.LINE_BREAK));
return res;
}
// Rendu d'une balise HTML ouvrante ou fermante
public List<StrTypePair> renderHtmlTag(HtmlTag tag, List<StrTypePair> attribs = null)
{
List<StrTypePair> res = new List<StrTypePair>();
_isAutoTag = _htmlAutoTags.Exists(v => v == tag.getTagName());
//on insère la balise
if(tag.getType() == HtmlTag.HTMLTagType.OPENTAG)
res.Add(new StrTypePair(HtmlTag.openSymbol[tag.getType()], (_isAutoTag) ? StrTypePair.StrType.AUTO_OPEN_TAG : StrTypePair.StrType.USR_OPEN_TAG));
else
res.Add(new StrTypePair(HtmlTag.openSymbol[tag.getType()], (_isAutoTag) ? StrTypePair.StrType.AUTO_END_TAG : StrTypePair.StrType.USR_END_TAG));
res.Add(new StrTypePair(tag.getTagName(), (_isAutoTag) ? StrTypePair.StrType.AUTO_TAG_NAME : StrTypePair.StrType.USR_TAG_NAME));
if (tag.getType() == HtmlTag.HTMLTagType.OPENTAG && attribs != null) res.AddRange(attribs);
res.Add(new StrTypePair(HtmlTag.endSymbol, (_isAutoTag) ? StrTypePair.StrType.AUTO_TAG : StrTypePair.StrType.USR_TAG));
return res;
}
public StrTypePair renderHtmlText(HtmlText txt)
{
return new StrTypePair(txt.getText(), (_isAutoTag) ? StrTypePair.StrType.AUTO_TEXT : StrTypePair.StrType.USR_TEXT);
}
public List<StrTypePair> renderHtmlTagAttribute(HtmlTagAttribute attr)
{
List<StrTypePair> res = new List<StrTypePair>();
res.Add(new StrTypePair(attr.getKey(), (_isAutoTag) ? StrTypePair.StrType.AUTO_TAG_ATTR_NAME : StrTypePair.StrType.USR_TAG_ATTR_NAME));
res.Add(new StrTypePair("=", (_isAutoTag) ? StrTypePair.StrType.AUTO_TAG_ATTR_AFFECT : StrTypePair.StrType.USR_TAG_ATTR_AFFECT));
string value = "\"" + attr.getValue() +"\"";
res.Add(new StrTypePair(value, (_isAutoTag) ? StrTypePair.StrType.AUTO_TAG_ATTR_VALUE : StrTypePair.StrType.USR_TAG_ATTR_VALUE));
return res;
}
public void autoIndent()
{
_indentLevel = 0;
//On parcourt tous les éléments du dictionnaire
foreach (StrTypePair elem in _code)
{
indentItem(elem);
}
}
private void indentItem(StrTypePair elem)
{
switch (elem.type)
{
case StrTypePair.StrType.USR_OPEN_TAG:
case StrTypePair.StrType.AUTO_OPEN_TAG:
_indentLevel++;
break;
case StrTypePair.StrType.USR_TAG_NAME:
case StrTypePair.StrType.AUTO_TAG_NAME:
if (HtmlElement.singleTags.Exists(v => v == elem.str))
{ // si ce n'est pas une balise simple, on annule la précédente auto-indentation
_indentLevel--;
_currentLineBreak.str = '\n' + new string(' ', indentSize * (_indentLevel));
}
break;
case StrTypePair.StrType.USR_END_TAG:
case StrTypePair.StrType.AUTO_END_TAG:
_indentLevel--;
_currentLineBreak.str = '\n' + new string(' ', indentSize * (_indentLevel));
break;
case StrTypePair.StrType.LINE_BREAK:
indentLine(elem);
break;
}
}
private void indentLine(StrTypePair elem)
{
// On stocke le retour à la ligne, s'il faut la modifier par la suite
_currentLineBreak = elem;
if (_indentLevel < 0) _indentLevel = 0;
_currentLineBreak.str = '\n' + new string(' ', indentSize * _indentLevel);
}
public void removeDoubleLineBreaks()
{
bool linebreak = false;
for (int i = 0; i < _code.Count; ++i)
{
if (_code[i].type == StrTypePair.StrType.LINE_BREAK)
{
if (linebreak)
{
_code.RemoveAt(i);
}
else
{
linebreak = true;
}
}
else
linebreak = false;
}
}
public void saveHTML(string filepath)
{
MdlRenduHtml mdlRendu = new MdlRenduHtml();
mdlRendu.renderPage();
string toSave = mdlRendu.getCode();
System.IO.StreamWriter file = new System.IO.StreamWriter(filepath);
file.WriteLine(toSave);
file.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*
*
* Le joueur ciblé passera son prochain tour.
*
* */
// include
using ChtemeleSurfaceApplication.Game_classes;
namespace ChtemeleSurfaceApplication.Effect_classes
{
class Freeze : Effect
{
private Player _player;
// Constructeur
public Freeze()
: base()
{
_type = EffectType.FREEZE;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.HTML_classes
{
public class HtmlTagAttribute
{
private string _key;
private string _value;
public HtmlTagAttribute(string key, string value)
{
_key = key;
_value = value;
}
public string getKey() { return _key; }
public string getValue() { return _value; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.HTML_classes
{
public abstract class HtmlTagContent
{
private int _uniqId;
private int _score;
private HtmlElement _parent;
private static int lastId = 0;
public HtmlTagContent()
{
_uniqId = lastId;
lastId++;
}
public HtmlTagContent(HtmlElement parent) : this()
{
_parent = parent;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.Carte_classes.Attaques
{
public class Error403 : AttaqueCarte
{
public Error403() : base() { }
public override void onValid()
{
// Elfe airien
}
public override void onPlay() { }
public override void onDelete() { }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.Game_classes
{
public class Combo
{
// Constantes, enumérations ======================================================================================================
public enum BonusCombo
{
FULLHAND,
NOERROR,
LASTTURN
}
// Variables membres ======================================================================================================
private string _code; // code de la combinaison
private int _codeScore; // Score généré par la combinaison
private int _nbCards; // Nombre de cartes de la combinaison
// Constructeurs ======================================================================================================
public Combo()
{
_code = "";
_codeScore = 0;
_nbCards = 0;
}
public Combo(Combo other)
{
_code = other.code;
_codeScore = other.score;
_nbCards = other.nbCards;
}
// Accesseurs / Mutateurs ======================================================================================================
public string code { get { return _code; } }
public int score { get { return _codeScore; } }
public int nbCards { get { return _nbCards; } }
// Fonctionnalités ======================================================================================================
public void addCard(HTMLCarte c)
{
_nbCards++;
_codeScore += c.score;
// TODO : trouver comment récupréer le code
}
public void reset()
{
_code = "";
_codeScore = 0;
_nbCards = 0;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication.HTML_classes;
namespace ChtemeleSurfaceApplication.Carte_classes
{
public class HTMLAttributeCarte : HTMLCarte
{
public string key;
//public string value; //Stocké dans textContent
public HTMLAttributeCarte(string k, string v, int s)
: base(s)
{
key = k;
textcontent = v;
}
public override void onValid()
{
if (HtmlElement._currentElement == null) return;
//On ajoute l'attribut à la balise courante
HtmlElement._currentElement.attributes.Add(new HtmlTagAttribute(key, textcontent));
//On donne des points au joueur
Game_classes.Game.getInstance.getCurPlayer().addPoint(_score);
//On met à joour la combo du joueur
Game_classes.Game.getInstance.getCurPlayer().lastCombo().addCard(this);
//On met à jour l'affichage (TODO : ça ne se fait pas ici normalement)
//SurfaceWindow1.getInstance.PageCode.ShowCode();
//SurfaceWindow1.getInstance.PageRendu.update();
}
public override void onPlay() { }
public override void onDelete() { }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ChtemeleSurfaceApplication.HTML_classes
{
public class HtmlPage
{
// Constantes, enumérations ======================================================================================================
public const string defaultDoctype = "<!DOCTYPE html>";
public const string cssDirectory = "Resources/css/";
// Variables membres ======================================================================================================
private HtmlElement _bodyTag; //Balise BODY
private HtmlElement _mainTag; //Balise HTML
private HtmlElement _headTag; //Balise HEAD
private string _doctype; //Balise DOCTYPE
private string _title; //Titre
private HtmlElement _cssTag; //Balise LINK
private HtmlElement _encodingTag; //Balise LINK
public string cssFile = cssDirectory + "chtemele.css";
// Constructeurs ======================================================================================================
public HtmlPage()
{
//Page exemple
/*_mainTag = new HtmlElement("html");
_mainTag.closeTag();
_doctype = defaultDoctype;
_title = "Bonjour, bienvenue, Hello world ! C'est tout !";
_headTag = new HtmlElement("head");
_headTag.closeTag();
_headTag.addContent(titleTag());
_mainTag.addContent(_headTag);
_bodyTag = new HtmlElement("body");
_bodyTag.attributes.Add(new HtmlTagAttribute("id", "Tamère"));
_bodyTag.closeTag();
_mainTag.addContent(_bodyTag);
_cssTag = new HtmlElement("link");
_cssTag.attributes.Add(new HtmlTagAttribute("type", "text/css"));
_cssTag.attributes.Add(new HtmlTagAttribute("rel", "stylesheet"));
_cssTag.attributes.Add(new HtmlTagAttribute("href", cssFile));
_headTag.addContent(_cssTag);
_encodingTag = new HtmlElement("meta");
_encodingTag.attributes.Add(new HtmlTagAttribute("charset", "UTF-8"));
_headTag.addContent(_encodingTag);
HtmlElement _baliseH1 = new HtmlElement("h1");
_baliseH1.addContent(new HtmlText("Ceci est un magnifique titre !"));
_baliseH1.attributes.Add(new HtmlTagAttribute("class", "montitre"));
_baliseH1.closeTag();
_bodyTag.addContent(_baliseH1);
HtmlElement _baliseH2 = new HtmlElement("h2");
_baliseH2.addContent(new HtmlText("Et ça, c'est un impressionnant sous-titre !"));
_baliseH2.closeTag();
_bodyTag.addContent(_baliseH2);
HtmlElement _baliseP = new HtmlElement("p");
_baliseP.addContent(new HtmlText("Lorem Ipsum et de toute façon je met le texte que je veux ce sera beautiful !"));
HtmlElement _baliseBR = new HtmlElement("br");
_baliseP.addContent(_baliseBR);
_baliseP.addContent(new HtmlText("N'est-ce pas ?"));
_baliseP.closeTag();
_bodyTag.addContent(_baliseP);
HtmlElement _baliseDIV1 = new HtmlElement("div");
_baliseDIV1.attributes.Add(new HtmlTagAttribute("id", "DTC"));
_baliseDIV1.closeTag();
_bodyTag.addContent(_baliseDIV1);
HtmlElement _baliseDIV2 = new HtmlElement("div");
_baliseDIV2.closeTag();
_baliseDIV1.addContent(_baliseDIV2);
HtmlElement _baliseH3 = new HtmlElement("h3");
_baliseH3.addContent(new HtmlText("Et ça, c'est un scintillant sous-sous-titre !"));
_baliseH3.closeTag();
_baliseDIV2.addContent(_baliseH3);
HtmlElement _baliseP2 = new HtmlElement("p");
_baliseP2.addContent(new HtmlText("Barquette !! Barquette !!! J'aimerais mon niveau deux, s'il vous plait."));
HtmlElement _baliseBR2 = new HtmlElement("br");
_baliseP2.addContent(_baliseBR2);
_baliseP2.addContent(new HtmlText("Je veux juste faire une longue phrase qui servira à tester le retour à la ligne non-automatique du TextBox."));
_baliseP2.closeTag();
_baliseDIV2.addContent(_baliseP2);*/
_mainTag = new HtmlElement("html");
_mainTag.closeTag();
_doctype = defaultDoctype;
_title = "Vous jouez actuellement à cHTeMeLe !";
_headTag = new HtmlElement("head");
_headTag.closeTag();
_headTag.addContent(titleTag());
_mainTag.addContent(_headTag);
_bodyTag = new HtmlElement("body");
//_bodyTag.attributes.Add(new HtmlTagAttribute("id", "Tamère"));
_bodyTag.closeTag();
_mainTag.addContent(_bodyTag);
_cssTag = new HtmlElement("link");
_cssTag.attributes.Add(new HtmlTagAttribute("type", "text/css"));
_cssTag.attributes.Add(new HtmlTagAttribute("rel", "stylesheet"));
_cssTag.attributes.Add(new HtmlTagAttribute("href", cssFile));
_headTag.addContent(_cssTag);
_encodingTag = new HtmlElement("meta");
_encodingTag.attributes.Add(new HtmlTagAttribute("charset", "UTF-8"));
_headTag.addContent(_encodingTag);
}
// Accesseurs / Mutateurs ======================================================================================================
public HtmlElement bodyTag() { return _bodyTag; }
public HtmlElement mainTag() { return _mainTag; }
public string doctype() { return _doctype; }
public string title() { return _title; }
public HtmlElement titleTag(){
HtmlElement ret = new HtmlElement("title");
ret.addContent(new HtmlText(_title));
ret.closeTag();
return ret;
}
public void changeCSS(string f)
{
cssFile = cssDirectory + f + ".css";
_cssTag.attributes.Clear();
_cssTag.attributes.Add(new HtmlTagAttribute("type", "text/css"));
_cssTag.attributes.Add(new HtmlTagAttribute("rel", "stylesheet"));
_cssTag.attributes.Add(new HtmlTagAttribute("href", cssFile));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.Carte_classes.Attaques
{
public class Freeze : AttaqueCarte
{
public Freeze() : base() { }
public override void onValid()
{
target.effects().Add(new Effect_classes.Freeze());
}
public override void onPlay() { }
public override void onDelete() { }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.Carte_classes.Addons
{
public class BrowserUpdate : AddonCarte
{
public BrowserUpdate() : base(){}
public override void onValid()
{
Game_classes.Player curplayer = Game_classes.Game.getInstance.getCurPlayer();
curplayer.effects().Add(new Effect_classes.BrowserUpdate());
}
public override void onPlay() { }
public override void onDelete() { }
}
}
<file_sep>using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// include
using ChtemeleSurfaceApplication.Game_classes;
namespace ChtemeleSurfaceApplication.File_classes
{
class FileReader
{
// URL absolu du fichier
private string FileUrl;
// entier le plus haut des parties (exemple dernière partie = game_85, DernierePArtie=85;)
private int DernierePartie;
// Nombre de tour effectué dans la partie
// Date de création de la partie
// Nombre de joueur dans la partie
//(variables défini en début de fichier :
// <!-- DATE / NB_JOUEUR / NB_TOUR (effectué) --> )
private int nbTourInFile;
private string datePartie; // variable stocké dans un fichier donc type string préféré
private int nbJoueur;
// Objet Game
public Game classeGame;
// faudra qu'on discute demain Val pour savoir comment on va s'y prendre pour la gestion des fichiers
// parce qu'il nous faut absolument un truc commun
// du genre :
/* quand on arrive sur le menu de demarrage choix -> voir ancienne partie OU commencer OU reprendre (avec fichier c'est possible j'explique pourquoi après)
*
*
* Visionner on pourra utiliser la fonction de listage
* Commencer une partie, il faudra savoir quel est le numéro de la derniere partie et l'incrementer
* Reprendre de même (listage) + effectuer d'autres test pour savoir si la partie est terminé
*
*
*
* comment on nomme les fichiers ? Les fichiers seront sauvegardé dans Resources/Savegame/game_1.html
* on peut imaginer le début du fichier de la sorte :
* <!-- DATE / NB_JOUEUR / NB_TOUR (effectué) -->
* Code ...
*
* On saura le numéro à choisir pour le prochain fichier grâce à ce petit code
*
*
*
*
*/
// Permet de récuperer tous les noms des fichiers dans un dossier précis dans la boucle
public void ListageFichier()
{
string temp = System.IO.Directory.GetCurrentDirectory();
temp = temp + "\\Resources\\Documentation";
String[] files = System.IO.Directory.GetFiles(temp);
for (int i = 0; i < files.Length; i++)
{
FileInfo F = new FileInfo(files[i]);
string test = Path.GetFileNameWithoutExtension(F.Name); // retourne le nom du fichier sans extension
}
}
// Test du plus grand fichier dans le listage
public void plusGrand(string FileName)
{
if (testNom(FileName))
{
// si fichier + petit on sort
string baseName = "game_";
int baseNameLength = baseName.Length;
char[] delimitation = { '_' };
string[] test = FileName.Split(delimitation, baseNameLength - 1);
int valeur = int.Parse(test[1]);
if (DernierePartie == null)
{
DernierePartie = 0;
}
else
{
if (valeur > DernierePartie)
DernierePartie = valeur;
}
}
}
// Sert à tester la base du nom, s'il n'est pas commun à celui désigner pour retourne faux
public bool testNom(string FileName)
{
string baseName = "game_";
int baseNameLength = baseName.Length;
char[] delimitation = { '_' };
string[] test = FileName.Split(delimitation, baseNameLength - 1);
if (test[0] == baseName)
return true;
return false;
}
// Test si une partie est finie
/*public bool testFinPartie(string FileName)
{
int nbSteps = classeGame.getActualnbSteps();
// test en temps réel
if(nbSteps < 10)
return false;
// test via le fichier (reprendre une partie)
if (nbTourInFile < 10)
return false;
return true;
}*/
// Permet de lire une ligne dans un fichier
public string readLineFile(string FileName, int line)
{
// lis tout le fichier en enregistrant chaque ligne
string[] lines = System.IO.File.ReadAllLines(FileName);
// enregistre dans temp la ligne voulu
string temp = lines[line];
// retourne la ligne dans un string
return temp;
}
// récupère le nombre de tour, date, nb_joueur
//<!-- DATE / NB_JOUEUR / NB_TOUR (effectué) -->
// (traitement de la premiere ligne du fichier game_XXX.html )
public void getInfoPartie(string FileName)
{
// récupère la première ligne du fichier
string firstLine = readLineFile(FileName, 0);
// Caractères à supprimer
char[] delimitation = { '<', '!','-','/', '>', ' '};
// traitement de la premiere ligne, supprime et ne laisse qu'un tableau de taille 3
string []temp = firstLine.Split(delimitation);
// récupère les valeurs
datePartie = temp[0];
nbJoueur = int.Parse(temp[1]); // conversion en int
nbTourInFile = int.Parse(temp[2]); // conversion en int
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChtemeleSurfaceApplication;
namespace ChtemeleSurfaceApplication.Game_classes
{
public class Player
{
// Constantes, enumérations ======================================================================================================
//Position du joueur sur la table de jeu
public const int OUT = 0;
public const int NORD = 1;
public const int EST = 2;
public const int SUD = 3;
public const int OUEST = 4;
// Noms des navigateurs
public const int FIREFOX = 0;
public const int CHROME = 1;
public const int IE = 2;
public const int SAFARI = 3;
public const int OPERA = 4;
public static Dictionary<int, string> browserNames = new Dictionary<int, string>
{
{0, "Firefox"},
{1, "Chrome"},
{2, "Internet Explorer"},
{3, "Safari"},
{4, "Opera"}
};
// Variables membres ======================================================================================================
public string name; //Nom du joueur
public int score; //score total accumulé
private Combo _lastCombo; //Dernière combinaison effectuée
private int _handSize; //taille max de la main du joueur;
private int _nbCards; //nombre de cartes en main.
private List<Effect> _effects; //Effets actifs sur le joueur
private int _position; //position du joueur (voir enumeration)
private int _browser; //navigateur
private Player _save; // Sauvegarde de l'état du joueur
// Constructeurs ======================================================================================================
// Paramètres : n nom du joueur
// p position du joueur
public Player(string n, int p, int b)
{
name = n;
score = 0;
_lastCombo = new Combo();
_handSize = Game.DEFAULT_HAND_SIZE;
_nbCards = _handSize;
_effects = new List<Effect>();
_position = p;
_browser = b;
_save = null;
}
// Accesseurs / Mutateurs ======================================================================================================
public Combo lastCombo(){ return _lastCombo;}
public List<Effect> effects() { return _effects; }
public int position() { return _position; }
public int browser { get { return _browser; } }
public int handSize { get { return _handSize; } }
public int nbCards { get { return _nbCards; } set { _nbCards = value; } }
// Fonctionnalités ======================================================================================================
// charge les données du joueur depuis une chaine de texte.
public void loadData()
{
}
// retourne les données du joueur sous forme de chaine de texte
public string getSaveData()
{
string ret = "";
return ret;
}
public void addPoint(int scoreAdd)
{
score += scoreAdd;
}
public void applyEffects()
{
// aucun effet n'a de sens sur le jeu. Cette focntion se contente de vider la liste des effets.
_effects.Clear();
}
public bool isFrozen()
{
foreach (Effect effect in _effects)
{
if (effect is Effect_classes.Freeze) return true;
}
return false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChtemeleSurfaceApplication.Carte_classes.Addons
{
public class Cafe : AddonCarte
{
public Cafe() : base(){}
public override void onValid()
{
// Ne fait rien
}
public override void onPlay() { }
public override void onDelete() { }
}
}
|
c73cf14c6ac1b65a9fec24166ae846a86b0752e1
|
[
"C#"
] | 46
|
C#
|
ChtemeleSurface/ChtemeleSurface
|
2bc664503bd04936784692c78d0d985ef9bdc9d1
|
0cb1d5ff0005579edb995beb7d3a0a29395ae549
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
using UnityEngine;
public class Test : MonoBehaviour
{
public UnityEngine.UI.Text outputText;
void Awake()
{
SetupFirebase();
SetupFacebook();
AppsFlyer.setIsDebug(true);
AppsFlyer.setAppsFlyerKey("YOUR_APPSFLYER_DEV_KEY_HERE");
}
void SetupFirebase()
{
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
// Set a flag here indiciating that Firebase is ready to use by your
// application.
Debug.Log("Firebase Ready");
outputText.text += "FirebaseReady!\n";
}
else
{
UnityEngine.Debug.LogError(System.String.Format(
"Could not resolve all Firebase dependencies: {0}", dependencyStatus));
// Firebase Unity SDK is not safe to use here.
outputText.text += System.String.Format(
"Could not resolve all Firebase dependencies: {0}", dependencyStatus) + "\n";
}
});
}
void SetupFacebook()
{
if (!FB.IsInitialized)
{
// Initialize the Facebook SDK
FB.Init(InitCallback, OnHideUnity);
}
else
{
// Already initialized, signal an app activation App Event
FB.ActivateApp();
}
}
private void InitCallback()
{
if (FB.IsInitialized)
{
// Signal an app activation App Event
FB.ActivateApp();
outputText.text += "Facebook Ready\n";
// Continue with Facebook SDK
// ...
}
else
{
Debug.Log("Failed to Initialize the Facebook SDK");
outputText.text += "Failed to Initialize the Facebook SDK\n";
}
}
private void OnHideUnity(bool isGameShown)
{
if (!isGameShown)
{
// Pause the game - we will need to hide
Time.timeScale = 0;
}
else
{
// Resume the game - we're getting focus again
Time.timeScale = 1;
}
}
}
|
59024b1fed3f6c4a103c0146f3e0db2db65c03c3
|
[
"C#"
] | 1
|
C#
|
egemencanguler/sdk
|
6dec21ed46ef26d23350c3100acc9093d8698aa4
|
14022d7d015fb70cf0dfee66bb652978b7e23827
|
refs/heads/master
|
<file_sep>using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace WpfApp3
{
public partial class shopContext : DbContext
{
public shopContext()
{
}
public shopContext(DbContextOptions<shopContext> options)
: base(options)
{
}
public virtual DbSet<DataOnIncome> DataOnIncome { get; set; }
public virtual DbSet<Invoice> Invoice { get; set; }
public virtual DbSet<Product> Product { get; set; }
public virtual DbSet<SellProduct> SellProduct { get; set; }
public virtual DbSet<ShelfLife> ShelfLife { get; set; }
public virtual DbSet<Supplier> Supplier { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=DESKTOP-80TT6SQ\\SQLEXPRESS;Database=shop;User Id=test;Password=<PASSWORD>;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.4-servicing-10062");
modelBuilder.Entity<DataOnIncome>(entity =>
{
entity.HasKey(e => e.IdDateOnIncome);
entity.ToTable("data_on_income");
entity.Property(e => e.IdDateOnIncome).HasColumnName("id_date_on_income");
entity.Property(e => e.Count).HasColumnName("count");
entity.Property(e => e.IdInvoice).HasColumnName("id_invoice");
entity.Property(e => e.IdProduct).HasColumnName("id_product");
entity.HasOne(d => d.IdInvoiceNavigation)
.WithMany(p => p.DataOnIncome)
.HasForeignKey(d => d.IdInvoice)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_data_on_income_invoice");
entity.HasOne(d => d.IdProductNavigation)
.WithMany(p => p.DataOnIncome)
.HasForeignKey(d => d.IdProduct)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_data_on_income_product");
});
modelBuilder.Entity<Invoice>(entity =>
{
entity.HasKey(e => e.Invoice1);
entity.ToTable("invoice");
entity.Property(e => e.Invoice1).HasColumnName("invoice");
entity.Property(e => e.Date)
.HasColumnName("date")
.HasColumnType("date");
entity.Property(e => e.IdSupplier).HasColumnName("id_supplier");
entity.HasOne(d => d.IdSupplierNavigation)
.WithMany(p => p.Invoice)
.HasForeignKey(d => d.IdSupplier)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_invoice_supplier");
});
modelBuilder.Entity<Product>(entity =>
{
entity.HasKey(e => e.IdProduct);
entity.ToTable("product");
entity.Property(e => e.IdProduct).HasColumnName("id_product");
entity.Property(e => e.Count).HasColumnName("count");
entity.Property(e => e.Name)
.IsRequired()
.HasColumnName("name")
.HasMaxLength(60)
.IsUnicode(false);
entity.Property(e => e.Price)
.HasColumnName("price")
.HasColumnType("money");
});
modelBuilder.Entity<SellProduct>(entity =>
{
entity.HasKey(e => e.IdSellProduct);
entity.ToTable("sell_product");
entity.Property(e => e.IdSellProduct).HasColumnName("id_sell_product");
entity.Property(e => e.Count).HasColumnName("count");
entity.Property(e => e.Date)
.HasColumnName("date")
.HasColumnType("date");
entity.Property(e => e.IdProduct).HasColumnName("id_product");
entity.HasOne(d => d.IdProductNavigation)
.WithMany(p => p.SellProduct)
.HasForeignKey(d => d.IdProduct)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_sell_product_product");
});
modelBuilder.Entity<ShelfLife>(entity =>
{
entity.HasKey(e => e.IdShelfLife);
entity.ToTable("shelf_life");
entity.Property(e => e.IdShelfLife)
.HasColumnName("id_shelf_life")
.ValueGeneratedNever();
entity.Property(e => e.IdInvoice).HasColumnName("id_invoice");
entity.Property(e => e.IdProduct).HasColumnName("id_product");
entity.Property(e => e.ShelfLife1).HasColumnName("shelf_life");
entity.HasOne(d => d.IdInvoiceNavigation)
.WithMany(p => p.ShelfLife)
.HasForeignKey(d => d.IdInvoice)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_shelf_life_invoice");
entity.HasOne(d => d.IdProductNavigation)
.WithMany(p => p.ShelfLife)
.HasForeignKey(d => d.IdProduct)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_shelf_life_product");
});
modelBuilder.Entity<Supplier>(entity =>
{
entity.HasKey(e => e.IdSupplier);
entity.ToTable("supplier");
entity.Property(e => e.IdSupplier).HasColumnName("id_supplier");
entity.Property(e => e.City)
.IsRequired()
.HasColumnName("city")
.HasMaxLength(25)
.IsUnicode(false);
entity.Property(e => e.Fax).HasColumnName("fax");
entity.Property(e => e.Name)
.IsRequired()
.HasColumnName("name")
.HasMaxLength(20)
.IsUnicode(false);
entity.Property(e => e.NameSupplier)
.IsRequired()
.HasColumnName("name_supplier")
.HasMaxLength(60)
.IsUnicode(false);
entity.Property(e => e.Patronymic)
.IsRequired()
.HasColumnName("patronymic")
.HasMaxLength(20)
.IsUnicode(false);
entity.Property(e => e.Surname)
.IsRequired()
.HasColumnName("surname")
.HasMaxLength(20)
.IsUnicode(false);
entity.Property(e => e.Telephone).HasColumnName("telephone");
});
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace WpfApp3
{
public partial class DataOnIncome
{
public int IdDateOnIncome { get; set; }
public int Count { get; set; }
public int IdProduct { get; set; }
public int IdInvoice { get; set; }
public virtual Invoice IdInvoiceNavigation { get; set; }
public virtual Product IdProductNavigation { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace WpfApp3
{
public partial class Supplier
{
public Supplier()
{
Invoice = new HashSet<Invoice>();
}
public int IdSupplier { get; set; }
public string NameSupplier { get; set; }
public string City { get; set; }
public string Surname { get; set; }
public string Name { get; set; }
public string Patronymic { get; set; }
public int Telephone { get; set; }
public int Fax { get; set; }
public virtual ICollection<Invoice> Invoice { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace WpfApp3
{
public partial class ShelfLife
{
public int IdShelfLife { get; set; }
public int IdProduct { get; set; }
public int IdInvoice { get; set; }
public int ShelfLife1 { get; set; }
public virtual Invoice IdInvoiceNavigation { get; set; }
public virtual Product IdProductNavigation { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp3
{
/// <summary>
/// Логика взаимодействия для SellPage.xaml
/// </summary>
public partial class SellPage : Page
{
public SellPage()
{
InitializeComponent();
createColums();
}
public void test()
{
MessageBox.Show("test");
}
public void createColums()
{
var inf = new List<SellProductTable>();
using (shopContext db = new shopContext())
{
foreach (var item in db.SellProduct.ToList())
{
SellProductTable product = new SellProductTable();
product.IdSellProduct = item.IdSellProduct;
product.Name = db.Product.Single(b => b.IdProduct == item.IdProduct).Name;
product.Count = item.Count;
product.Date = item.Date;
inf.Add(product);
}
}
database.Columns.Add(new DataGridTextColumn()
{
Header = "ID",
Binding = new Binding("IdSellProduct")
});
database.Columns.Add(new DataGridTextColumn()
{
Header = "Название продукта",
Binding = new Binding("Name")
});
database.Columns.Add(new DataGridTextColumn()
{
Header = "Количество проданных товаров",
Binding = new Binding("Count")
});
database.Columns.Add(new DataGridTextColumn()
{
Header = "Дата продажи",
Binding = new Binding("Date")
});
database.AutoGenerateColumns = false;
database.ItemsSource = inf;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SellSearchWindow search = new SellSearchWindow();
search.Show();
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace WpfApp3
{
public partial class Invoice
{
public Invoice()
{
DataOnIncome = new HashSet<DataOnIncome>();
ShelfLife = new HashSet<ShelfLife>();
}
public int Invoice1 { get; set; }
public DateTime Date { get; set; }
public int IdSupplier { get; set; }
public virtual Supplier IdSupplierNavigation { get; set; }
public virtual ICollection<DataOnIncome> DataOnIncome { get; set; }
public virtual ICollection<ShelfLife> ShelfLife { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace WpfApp3
{
public partial class Product
{
public Product()
{
DataOnIncome = new HashSet<DataOnIncome>();
SellProduct = new HashSet<SellProduct>();
ShelfLife = new HashSet<ShelfLife>();
}
public int IdProduct { get; set; }
public string Name { get; set; }
public int Count { get; set; }
public decimal Price { get; set; }
public virtual ICollection<DataOnIncome> DataOnIncome { get; set; }
public virtual ICollection<SellProduct> SellProduct { get; set; }
public virtual ICollection<ShelfLife> ShelfLife { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace WpfApp3
{
public partial class SellProduct
{
public int IdSellProduct { get; set; }
public int Count { get; set; }
public int IdProduct { get; set; }
public DateTime Date { get; set; }
public virtual Product IdProductNavigation { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp3
{
public partial class SellProductTable
{
public int IdSellProduct { get; set; }
public string Name { get; set; }
public int Count { get; set; }
public int IdProduct { get; set; }
public DateTime Date { get; set; }
}
}
|
9143a056c45eb450c2043bd29bb146f5d992d444
|
[
"C#"
] | 9
|
C#
|
masterworgen/urtk-coursework
|
faedca63fb39fe8b1d8a271e951ab4c412810a5c
|
1ab0223cf42be24ec1e0e31b29fb8d96e29c5e9b
|
refs/heads/master
|
<repo_name>ihrigb/camera-booth<file_sep>/pi/lib/python3.6/site-packages/tfatool-2.5.0.dist-info/DESCRIPTION.rst
TFATool: Toshiba FlashAir Tool
==============================
This package provides easy access to
Toshiba's FlashAir wireless SD card. As a library,
a simple abstraction of the FlashAir API is provided. As a set of
scripts, `tfatool` the user is given a way of synchronizing/mirroring
files and configuring the device from the command line.
Package contents at a glance
============================
* ``flashair-util``: a command line tool for mirroring and listing files on FlashAir
* ``flashair-config``: a command line tool for configuring FlashAir
* ``tfatool.command``: abstraction of FlashAir's `command.cgi <https://flashair-developers.com/en/documents/api/commandcgi/>`_
* ``tfatool.upload``: abstraction of FlashAir's `upload.cgi <https://flashair-developers.com/en/documents/api/uploadcgi/>`_
* ``tfatool.config``: abstraction of FlashAir's `config.cgi <https://flashair-developers.com/en/documents/api/configcgi/>`_
* ``tfatool.sync``: functions for synchronizing local dirs with remote FlashAir dirs
Command line usage at a glance
==============================
1. Monitor FlashAir for new JPEGs, download to ~/Photos
``flashair-util -s -d /home/tad/Photos --only-jpg``
2. Monitor working dir for new files, upload to FlashAir
``flashair-util -s -y up``
3. Monitor a local and remote dir for new files, sync them
``flashair-util -s -y both``
4. Sync down the 10 most recent to a local dir, then quit
``flashair-util -S time -d images/new/``
5. Sync up all files created in 1999 and afterwards
``flashair-util -S all -t 1999``
6. Sync down files created between Jan 23rd and Jan 26th
``flashair-util -S all -t 1-23 -T 01/26``
7. Sync files (up AND down) created this afternoon
``flashair-util -S all -t 12:00 -T 16:00 -y both``
8. Sync files up created after a very specific date/time
``flashair-util -S all -t '2016-1-25 11:38:22'``
9. Sync (up and down) 5 most recent files of a certain name
``flashair-util -S time -k 'IMG-08.+\.raw' -y both``
10. List files on FlashAir created after a certain time
``flashair-util -l -t '1-21-2016 8:30:11'``
11. Change FlashAir network SSID
``flashair-config --wifi-ssid myflashairnetwork``
12. Show FlashAir network password & firmware version
``flashair-config --show-wifi-key --show-fw-version``
More
====
See https://github.com/TadLeonard/tfatool for complete documentation.
<file_sep>/pi/sync.py
from tfatool import sync
import re
import sys
import time
is_running = True
filter_jpg = lambda f: f.filename.lower().endswith(".jpg")
while is_running:
try:
print("GO")
monitor = sync.Monitor(filter_jpg, local_dir="images", remote_dir="/DCIM/112_PANA")
monitor.sync_down()
monitor.join()
except KeyboardInterrupt:
print("Received KeyboardInterrupt.")
is_running = False
except:
print("Exception while syncing")
try:
time.sleep(5000)
except KeyboardInterrupt:
is_running = False
monitor.stop()
monitor.join()
sys.exit(0)
<file_sep>/pi/view.py
import logging
import sys
import threading
import time
import pygame
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
class Viewer:
def __init__(self, fullscreen = True):
self._fullscreen = fullscreen
pygame.init()
displayinfo = pygame.display.Info()
self._size = (displayinfo.current_w, displayinfo.current_h)
self._window_surface = pygame.display.set_mode(self._size, pygame.FULLSCREEN, 32)
def run(self):
done = False
while not done:
event = pygame.event.wait()
if event.type == pygame.KEYDOWN and event.key == pygame.K_F11:
if self._fullscreen:
pygame.display.set_mode(self._size)
self._fullscreen = not self._fullscreen
else:
pygame.display.set_mode(self._size, pygame.FULLSCREEN)
self._fullscreen = not self._fullscreen
if event.type == pygame.QUIT:
done = True
pygame.quit()
def update(self, src_path):
try:
img = pygame.transform.scale(pygame.image.load(src_path), self._size)
self._window_surface.blit(img, (0, 0))
pygame.display.flip()
except:
logging.error("Displaying a new image failed.")
class ViewFileSystemEventHandler(FileSystemEventHandler):
def __init__(self, viewer):
self._viewer = viewer
def on_created(self, event):
self.event(event)
def on_modified(self, event):
self.event(event)
def event(self, event):
if event.is_directory:
return
self._viewer.update(event.src_path)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
viewer = Viewer()
event_handler = ViewFileSystemEventHandler(viewer)
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
viewer.run()
observer.stop()
observer.join()
<file_sep>/pi/test.py
import pygame
import time
from pygame.locals import *
pygame.init()
displayinfo = pygame.display.Info()
print(displayinfo.current_w)
print(displayinfo.current_h)
WIDTH = displayinfo.current_w
HEIGHT = displayinfo.current_h
size = (WIDTH, HEIGHT)
windowSurface = pygame.display.set_mode(size, pygame.FULLSCREEN, 32)
img = pygame.image.load("images/P1120292.JPG")
img = pygame.transform.scale(img, size)
fullscreen = True
done = False
while not done:
event = pygame.event.wait()
if event.type == pygame.KEYDOWN and event.key == pygame.K_F11:
if fullscreen:
pygame.display.set_mode(size)
fullscreen = not fullscreen
else:
pygame.display.set_mode(size, pygame.FULLSCREEN)
fullscreen = not fullscreen
if event.type == pygame.QUIT:
done = True
break
windowSurface.blit(img, (0, 0))
pygame.display.flip()
pygame.quit()
#sync.down_by_arrival(local_dir="/tmp/images", remote_dir="/DCIM/112_PANA")
#import re
#dirs = command.list_files(remote_dir="/DCIM")
#for dir in dirs:
# print(">>> " + dir.filename)
# if re.match(r'^[0-9]{3}_PANA$', dir.filename):
# print(">>> >>> " + dir.filename)
# subdir = "/DCIM/" + dir.filename
# files = command.list_files(remote_dir=subdir)
# for file in files:
# print(">>> >>> >>> " + file.filename)
# monitor = sync.Monitor(local_dir="/tmp/img", remote_dir="/DCIM/112_PANA")
# monitor.sync_down()
<file_sep>/arduino/camera_booth/camera_booth.ino
const int startCountdown = 5;
const byte opto_focus = 2;
const byte opto_shutter = 3;
const byte button = 11;
// seven-segment pins
const byte a = 4;
const byte b = 5;
const byte c = 6;
const byte d = 7;
const byte e = 8;
const byte f = 9;
const byte g = 10;
const byte sevenSegPins[7] = {a, b, c, d, e, f, g};
boolean trigger = false;
int buttonState;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void on(byte pin) {
digitalWrite(pin, HIGH);
}
void off(byte pin) {
digitalWrite(pin, LOW);
}
void displayDigit(int digit) {
// segment a
if (digit != 1 && digit != 4) {
on(a);
} else {
off(a);
}
// segment b
if (digit != 5 && digit != 6) {
on(b);
} else {
off(b);
}
// segment c
if (digit != 2) {
on(c);
} else {
off(c);
}
// segment d
if (digit != 1 && digit != 4 && digit != 7) {
on(d);
} else {
off(d);
}
// segment e
if (digit == 2 || digit == 6 || digit == 8 || digit == 0) {
on(e);
} else {
off(e);
}
// segment f
if (digit != 1 && digit != 2 && digit != 3 && digit != 7) {
on(f);
} else {
off(f);
}
// segment g
if (digit != 0 && digit != 1 && digit != 7) {
on(g);
} else {
off(g);
}
}
void turnLedOff() {
for (byte pin = 0; pin < (sizeof(sevenSegPins) / sizeof(byte)); pin++) {
off(sevenSegPins[pin]);
}
}
void focus() {
on(opto_focus);
}
void shutter() {
on(opto_shutter);
}
void resetCamera() {
off(opto_shutter);
off(opto_focus);
}
void takePhoto() {
for (int i = startCountdown; i >= 0; i--) {
displayDigit(i);
if (i == 2) {
focus();
}
if (i == 0) {
shutter();
delay(200);
resetCamera();
delay(800);
break;
}
delay(1000);
}
turnLedOff();
}
void setup() {
// put your setup code here, to run once:
//Serial.begin(115200);
pinMode(button, INPUT);
pinMode(opto_focus, OUTPUT);
pinMode(opto_shutter, OUTPUT);
for (byte pin = 0; pin < (sizeof(sevenSegPins) / sizeof(byte)); pin++) {
pinMode(sevenSegPins[pin], OUTPUT);
}
}
void loop() {
// put your main code here, to run repeatedly:
int reading = digitalRead(button);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
trigger = true;
}
}
}
lastButtonState = reading;
if (trigger) {
trigger = false;
takePhoto();
}
}
<file_sep>/README.md
# Camera Booth
This is the code of a project, that uses an Arduino remote controlled camera in box. More to come.
|
9d735e0ce20546d279f9d5b0a174096543ecb39f
|
[
"Markdown",
"Python",
"C++",
"reStructuredText"
] | 6
|
reStructuredText
|
ihrigb/camera-booth
|
5177fb3aeb71c53501b8fdf353b580e6ea9d2cff
|
2ef91bf3d0ab2543be4bd9a0211a5b9da69b8362
|
refs/heads/master
|
<repo_name>gpkc/simple_rest<file_sep>/simple_rest/views.py
from flask_apispec import MethodResource, use_kwargs, doc, marshal_with
from webargs import fields
from flask import abort
class UserView(MethodResource):
pass
class UsersView(MethodResource):
pass
<file_sep>/tests/test_views.py
class TestUserViews:
def test_post_user(self, post_user):
pass
def test_get_user(self, post_user, get_user):
pass
def test_put_user(self, post_user, get_user, put_user):
pass
def test_delete_user(self, post_user, get_user, delete_user):
pass
<file_sep>/simple_rest/validators.py
from webargs import fields, ValidationError
def validate_age(age):
if age < 0:
raise ValidationError('Age must be greater than 0.')
<file_sep>/simple_rest/app.py
from apispec import APISpec
from flask import Flask
from flask_apispec import FlaskApiSpec, marshal_with
from flask_cors import CORS
from schemas import ErrorSchema
# Create app
app = Flask(__name__)
app.config['APISPEC_SPEC'] = APISpec(
title='simple_rest',
version='v1',
plugins=('apispec.ext.marshmallow', ))
app.config['APISPEC_SWAGGER_URL'] = '/swagger/'
# Register views
# from .views import ...
# app.add_url_rule('<route>', view_func=<myview>.as_view('<viewname>'))
# ...
# Register view on apispec
docs = FlaskApiSpec(app)
# docs.register(<myview>)
# ...
# Register RESTful error handler
@app.errorhandler(404)
@marshal_with(ErrorSchema, code=404)
def handle_not_found(err):
exc = getattr(err, 'description')
if exc:
message = err.description
else:
message = ['Not found']
return {
'status': 'fail',
'message': message
}, 404
# Enable CORS
CORS(app)
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/requirements.txt
Flask==0.12.2
flask-apispec==0.6.0.post0
Flask-Cors==3.0.3
marshmallow==2.15.0
webargs==2.0.0
pytest==3.5.0
<file_sep>/simple_rest/store.py
store = {}
<file_sep>/tests/conftest.py
import json
import pytest
from store import store
@pytest.fixture
def app():
from app import app as app_
ctx = app_.test_request_context()
ctx.push()
yield app_
ctx.pop()
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture(autouse=True, scope='function')
def setup_db(app):
# create_all step for a real database
yield
store.clear()
@pytest.fixture
def send_request(client):
def send_request_(endpoint, method, headers=None, **kwargs):
if not headers:
headers = {}
response = getattr(client, method)(
endpoint,
data=json.dumps(dict(**kwargs)),
content_type='application/json',
headers=headers
)
if response.data:
data = json.loads(response.data.decode())
else:
data = {}
return response, data
return send_request_
@pytest.fixture
def post_user(send_request):
pass
@pytest.fixture
def get_user(send_request):
pass
@pytest.fixture
def put_user(send_request):
pass
@pytest.fixture
def delete_user(send_request):
pass
<file_sep>/simple_rest/schemas.py
from marshmallow import fields, Schema
class UserSchema(Schema):
pass
class UserResponseSchema(Schema):
pass
class UsersResponseSchema(Schema):
pass
class ErrorSchema(Schema):
status = fields.String()
message = fields.String()
|
0f4632fec8c1f1de608800eb44d0bb232c4df54d
|
[
"Python",
"Text"
] | 8
|
Python
|
gpkc/simple_rest
|
7f6d09a98190bdde042c5c04c5de8f3260d2387a
|
d0611c890140636da091a528e3f23b28e126e787
|
refs/heads/master
|
<file_sep>#include <stdio.h>
int main()
{
printf("\thelloworld\n\t\b\\\n");
printf("bonjour le monde!\n\n");
}<file_sep>#include <stdio.h>
/*strugging with ob1. Wrting code to step through the increments of the while loop.
successful! But still confused. ????*/
int main()
{
long nc;
int w;
nc = 0;
w = getchar();
/* example did NOT have brackets around the while statement. Seems you don't need them if only one,
but necessary for multiple. */
while (w != '\n') { // wow..... double quotes failed here. but sinmgle quotes ok.
putchar(w);
w = getchar();
++nc;
printf("\tcount: %.0ld\n", nc); // double quotes NEEDED here.
}
printf("\tfinal: %ld\n", nc);
return 0;
}
// int main()
// {
// double nc;
// for (nc = 0; getchar() != EOF; nc++)
// printf("%.0f\n", nc);
// printf("final count: %.0f\n", nc);
// }
<file_sep>#include <stdio.h>
/* comments! third pass at converting celsius to fahrenheit in a loop. -- floats, for loop.
*/
int main()
{
float fahr, celsius;
int start, stop, step;
start = 0;
stop = 300;
step = 20;
fahr = start; /* NB - farh REMAINS float type, even though start is int type.*/
printf("\nFahr\tCelsius\n");
printf("---------------\n");
while (fahr <= stop) {
celsius = (5.0/9.0) * (fahr-32.0);
printf("%3.0f\t%6.1f\n", fahr, celsius);
fahr = fahr + step;
}
start = 0;
stop = 100;
step = 10;
celsius = start;
printf("\nCelius\tFahrenheit\n");
printf("---------------\n");
while (celsius <= stop) {
fahr = (celsius+32) * (9.0/5.0);
printf("%4.0f\t%6.1f\n", celsius, fahr);
celsius = celsius + step;
}
int fh;
printf("\nFahr\tCelsius\n");
printf("---------------\n");
for (fh = 300; fh >= 0; fh = fh - 20)
printf("%3d \t%6.1f\n", fh, (5.0/9.0) * (fh-32));
printf("\n\n");
}<file_sep>#include <stdio.h>
/*
int main()
{
int c;
// below asks the terminal for text input -- zero to many characters e.g monkey
c = getchar();
while (c != EOF) {
putchar(c);
printf("\n");
// below advances one letter OF THE GIVEN STRING??? e.g. m, then o, then n...
// how can the same method do both these things?
c = getchar();
}
}
*/
int main()
{
int c;
while ((c = getchar()) != EOF) {
// putchar DOES require an argument.
putchar(c);
}
}
// int main()
// {
// int word, c;
// word = getchar();
// // nope - the below fails :(
// // error: too many arguments to function call, expected 0, have 1
// // c = getchar(word);
// c = getchar(word);
// while (c != EOF) {
// putchar(c);
// printf("\n");
// c = getchar(word);
// }
// }
|
bc686870f8a08937681738b9ec690d270e986832
|
[
"C"
] | 4
|
C
|
tremlab/C_babysteps
|
a1c9e86fc3062ea9785e36d39feeca2cbc196c54
|
fe1ce048c6bb5b051613d151ee29ffa2a7eda91c
|
refs/heads/master
|
<repo_name>TildeBeta/Project-Euler<file_sep>/Solutions/Euler4.py
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
Solution: 906609
"""
def is_palindrome(num):
num = str(num)
return num == num[::-1]
palindromes = []
for x in range(100, 999):
for y in range(100, 999):
if is_palindrome(x*y):
palindromes.append(x*y)
print(max(palindromes))
<file_sep>/README.md
# Project-Euler
Solutions to Project Euler problems made in Python.
The problem is usually a multiline comment at the top. If it's missing then it was probably really long.
<file_sep>/Solutions/Euler3.py
"""
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
Solution: 6857
"""
def largest_prime_factorial(n):
for i in range(2, 1000000000):
while not n % i:
n /= i
if n in [1, i]:
return i
print(largest_prime_factorial(600851475143))
<file_sep>/Solutions/Euler5.py
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
Solution: 232792560
"""
def divisible_to_20(num):
# We can rule out 1, 2, 3,
# 4, 5, 6, 7, 8, 9, and 10
for i in range(11, 20):
if num % i != 0:
return False
return True
i = 20
while True:
if divisible_to_20(i):
print(i)
break
else:
i += 20
|
25ead3ade5508e97c02ee772c1fec2a4559a6766
|
[
"Markdown",
"Python"
] | 4
|
Python
|
TildeBeta/Project-Euler
|
e91c23692979ca9a44fa5da2c32a0d4c4a97ff72
|
4d6bebdb6fdc9658cef673e837bbb12e66a35b1d
|
refs/heads/master
|
<file_sep>package com.chen.cxProject.Controller;
import com.chen.cxProject.Service.Test03Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test03")
public class Test03Controller {
@Autowired
Test03Service service03;
@RequestMapping("/01")
public String test01(){
service03.testServie();
return "success02";
}
}
<file_sep>package com.chen.cxProject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CxApplication {
//chenxin003-function01-02
public static void main(String[] args) {
SpringApplication.run(CxApplication.class, args);
}
}
<file_sep>package com.chen.cxProject.Service;
import org.springframework.stereotype.Service;
@Service
public class Test03Service {
public void testServie(){
System.out.println("testService...");
}
}
<file_sep>package com.chen.cxProject.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test01")
public class Test01Controller {
@RequestMapping("/01")
public String Test01(){
return "success";
}
}
|
e2e4a427c2fdf83df9fe1e04e9832a4fc54e21e4
|
[
"Java"
] | 4
|
Java
|
welldone1915/CxProject02
|
7263166de901a5e3a849bedd95886f94efe60a7c
|
a15e82f973112bfa86ba8a954d132b256035f88e
|
refs/heads/master
|
<repo_name>zygeilit/page-layouts<file_sep>/server.js
var connect = require('connect');
var HttpDispatcher = require('httpdispatcher');
var dispatcher = new HttpDispatcher();
var fs = require('fs');
var util = require('util');
var path = require('path');
var serveStatic = require('serve-static')
var port = 8080;
// 承载页
dispatcher.onGet('/flow', function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-cache' });
fs.readFile('./flow2-2.html', null, function(error, data){
if(error) {
res.writeHead(404);
res.write('File not fount!');
} else {
res.write(data);
}
res.end();
});
});
dispatcher.onGet('/svg-arrow', function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-cache' });
fs.readFile('./svg-arrow.html', null, function(error, data){
if(error) {
res.writeHead(404);
res.write('File not fount!');
} else {
res.write(data);
}
res.end();
});
});
(new connect())
// 输出请求连接
.use(function logger(req, res, next) {
console.log('%s %s', req.method, req.url);
next();
})
// 返回资源文件
.use(function staticFiles(req, res, next) {
var filePath = '.' + req.url;
var extname = path.extname(filePath);
var contentType = '';
var isStaticFile = false;
switch (extname) {
case '.js':
contentType = 'text/javascript';
isStaticFile = true;
break;
case '.css':
contentType = 'text/css';
isStaticFile = true;
break;
case '.png':
case '.jpg':
case '.gif':
contentType = 'image/' + extname.replace('\.', '');
isStaticFile = true;
// 提出images 里面的style
filePath = filePath.replace(/styles\//, '');
break;
default: break;
}
if(isStaticFile) {
fs.readFile(filePath, function(error, content) {
if (error) {
res.writeHead(404);
res.write('File not fount!');
}
else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
res.end();
});
} else {
next();
}
})
// 接口路由
.use(function interfaces(req, res, next) {
dispatcher.dispatch(req, res);
})
.listen(port)
|
d48e096d125003dd7baf81e1011f08d77f4bcce9
|
[
"JavaScript"
] | 1
|
JavaScript
|
zygeilit/page-layouts
|
49149c496d723df0406cf5bcaa6f11aa26897fa9
|
61df1dc41aad393669f7b96e671ebab9d517848c
|
refs/heads/master
|
<repo_name>fangye945a/linux_c_example<file_sep>/tcp_server_example/socket_server.h
/*******************************************************************************
* Copyright (C) 2017 ZOOMLION
*
* All rights reserved.
*
* Contributors:
* jea.long initial version
*
*******************************************************************************/
/**
* @file socket_server.h
*
*/
#ifndef SOCKET_SERVER_H
#define SOCKET_SERVER_H
# define POLLRDHUP 0x2000
#ifdef __cplusplus
extern "C"
{
#endif
/**
* TYPEDEFS
*/
typedef void (*socketServerCb_t)( int clientFd );
/**
* INCLUDES
*/
#include <stdint.h>
//#include "hal_types.h"
/**
* CONSTANTS
*/
#define MAX_CLIENTS 5
/*
* serverSocketInit - initialises the server.
*/
int32_t socketServerInit( uint32_t port );
/*
* serverSocketConfig - initialises the server.
*/
int32_t socketServerConfig(socketServerCb_t rxCb, socketServerCb_t connectCb);
/*
* getClientFds - get clients fd's.
*/
void socketServerGetClientFds(int *fds, int maxFds);
/*
* getClientFds - get clients fd's.
*/
uint32_t socketServerGetNumClients(void);
/*
* socketSeverPoll - services the Socket events.
*/
void socketServerPoll(int clinetFd, int revent);
/*
* socketSeverSendAllclients - Send a buffer to all clients.
*/
int32_t socketServerSendAllclients(uint8_t* buf, uint32_t len);
/*
* socketSeverSend - Send a buffer to a clients.
*/
int32_t socketServerSend(uint8_t* buf, uint32_t len, int32_t fdClient);
/*
* socketSeverClose - Closes the client connections.
*/
void socketServerClose(void);
#ifdef __cplusplus
}
#endif
#endif /* SOCKET_SERVER_H */
<file_sep>/tcp_server_example/socket_server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <errno.h>
#include <stdint.h>
#include "socket_server.h"
/**
* TYPEDEFS
*/
typedef struct
{
void *next;
int socketFd;
socklen_t cli_len;
struct sockaddr_in cli_addr;
} socketRecord_t;
/**
* GLOBAL VARIABLES
*/
socketRecord_t *socketRecordHead = NULL;
socketServerCb_t socketServerRxCb;
socketServerCb_t socketServerConnectCb;
/**
* @fn createSocketRec
* @brief create a socket and add a rec fto the list.
* @param table
* @param rmTimer
* @return new clint fd
*/
int createSocketRec( void )
{
int tr=1;
socketRecord_t *srchRec;
socketRecord_t *newSocket = malloc( sizeof( socketRecord_t ) );
//open a new client connection with the listening socket (at head of list)
newSocket->cli_len = sizeof(newSocket->cli_addr);
//Head is always the listening socket
newSocket->socketFd = accept(socketRecordHead->socketFd,
(struct sockaddr *) &(newSocket->cli_addr),
&(newSocket->cli_len));
if (newSocket->socketFd < 0)
printf("accept error!");
// Set the socket option SO_REUSEADDR to reduce the chance of a
// "Address Already in Use" error on the bind
setsockopt(newSocket->socketFd,SOL_SOCKET,SO_REUSEADDR,&tr,sizeof(int));
// Set the fd to none blocking
fcntl(newSocket->socketFd, F_SETFL, O_NONBLOCK);
newSocket->next = NULL;
//find the end of the list and add the record
srchRec = socketRecordHead;
// Stop at the last record
while ( srchRec->next )
srchRec = srchRec->next;
// Add to the list
srchRec->next = newSocket;
return(newSocket->socketFd);
}
/**
* @fn deleteSocketRec
* @brief Delete a rec from list.
* @param table
* @param rmTimer
* @return none
*/
void deleteSocketRec( int rmSocketFd )
{
socketRecord_t *srchRec, *prevRec=NULL;
// Head of the timer list
srchRec = socketRecordHead;
// Stop when rec found or at the end
while ( (srchRec->socketFd != rmSocketFd) && (srchRec->next) )
{
prevRec = srchRec;
// over to next
srchRec = srchRec->next;
}
if (srchRec->socketFd != rmSocketFd)
{
printf("deleteSocketRec: record not found");
return;
}
// Does the record exist
if ( srchRec )
{
// delete the timer from the list
if ( prevRec == NULL )
{
//trying to remove first rec, which is always the listining socket
printf("deleteSocketRec: removing first rec, which is always the listining socket.");
return;
}
//remove record from list
prevRec->next = srchRec->next;
close(srchRec->socketFd);
free(srchRec);
}
}
/**
* @fn serverSocketInit
* @brief initialises the server.
* @param
* @return Status
*/
int32_t socketServerInit( uint32_t port )
{
struct sockaddr_in serv_addr;
int stat, tr=1;
if(socketRecordHead == NULL)
{
// New record
socketRecord_t *lsSocket = malloc( sizeof( socketRecord_t ) );
lsSocket->socketFd = socket(AF_INET, SOCK_STREAM, 0);
if (lsSocket->socketFd < 0)
{
printf("opening socket fail");
return -1;
}
// Set the socket option SO_REUSEADDR to reduce the chance of a
// "Address Already in Use" error on the bind
setsockopt(lsSocket->socketFd, SOL_SOCKET, SO_REUSEADDR, &tr, sizeof(int));
// Set the fd to none blocking
fcntl(lsSocket->socketFd, F_SETFL, O_NONBLOCK);
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
stat = bind(lsSocket->socketFd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr));
if ( stat < 0)
{
printf("binding error: %s\n", strerror( errno ) );
return -1;
}
//will have MAX_CLIENTS pending open client requests
listen(lsSocket->socketFd, MAX_CLIENTS);
lsSocket->next = NULL;
//Head is always the listening socket
socketRecordHead = lsSocket;
}
return 0;
}
/**
* @fn serverSocketConfig
* @brief register the Rx Callback.
* @param
* @return Status
*/
int32_t socketServerConfig(socketServerCb_t rxCb, socketServerCb_t connectCb)
{
socketServerRxCb = rxCb;
socketServerConnectCb = connectCb;
return 0;
}
/**
* @fn socketSeverGetClientFds()
* @brief get clients fd's.
* @param none
* @return list of Timerfd's
*/
void socketServerGetClientFds(int *fds, int maxFds)
{
uint32_t recordCnt=0;
socketRecord_t *srchRec;
// Head of the timer list
srchRec = socketRecordHead;
// Stop when at the end or max is reached
while ( (srchRec) && (recordCnt < maxFds) )
{
fds[recordCnt++] = srchRec->socketFd;
srchRec = srchRec->next;
}
return;
}
/**
* @fn socketSeverGetNumClients()
* @brief get clients fd's.
* @param none
* @return list of Timerfd's
*/
uint32_t socketServerGetNumClients(void)
{
uint32_t recordCnt=0;
socketRecord_t *srchRec;
// Head of the timer list
srchRec = socketRecordHead;
if(srchRec==NULL)
{
printf("socketSeverGetNumClients: socketRecordHead NULL\n");
return -1;
}
// Stop when rec found or at the end
while ( srchRec )
{
srchRec = srchRec->next;
recordCnt++;
}
// printf("socketSeverGetNumClients %d", recordCnt);
return (recordCnt);
}
/**
* @fn socketSeverPoll()
* @brief services the Socket events.
* @param clinetFd - Fd to services
* @param revent - event to services
* @return none
*/
void socketServerPoll(int clientFd, int revent)
{
//is this a new connection on the listening socket
if(clientFd == socketRecordHead->socketFd)
{
int newClientFd = createSocketRec();
if(socketServerConnectCb)
{
socketServerConnectCb(newClientFd);
}
}
else
{
//this is a client socket is it a input or shutdown event
if (revent & POLLIN)
{
//its a Rx event
if(socketServerRxCb)
{
socketServerRxCb(clientFd);
}
}
if (revent & POLLRDHUP)
{
//its a shut down close the socket
printf("Client fd:%d disconnected\n", clientFd);
//remove the record and close the socket
deleteSocketRec(clientFd);
}
}
//write(clientSockFd,"I got your message",18);
return;
}
/**
* @fn socketSeverSend
* @brief Send a buffer to a clients.
* @param uint8* srpcMsg - message to be sent
* int32 fdClient - Client fd
* @return Status
*/
int32_t socketServerSend(uint8_t* buf, uint32_t len, int32_t fdClient)
{
int32_t rtn;
if(fdClient)
{
rtn = write(fdClient, buf, len);
if (rtn < 0)
{
printf("write date to fdClient %d error!", fdClient);
return rtn;
}
}
return 0;
}
/**
* @fn socketSeverSendAllclients
* @brief Send a buffer to all clients.
* @param uint8* srpcMsg - message to be sent
* @return Status
*/
int32_t socketServerSendAllclients(uint8_t* buf, uint32_t len)
{
int rtn;
socketRecord_t *srchRec;
srchRec = socketRecordHead->next;
// Stop when at the end or max is reached
while ( srchRec )
{
rtn = write(srchRec->socketFd, buf, len);
if (rtn < 0)
{
printf("write date to socket %d error!", srchRec->socketFd);
printf("closing client socket");
deleteSocketRec(srchRec->socketFd);
return rtn;
}
srchRec = srchRec->next;
}
return 0;
}
/**
* @fn socketSeverClose
* @brief Closes the client connections.
* @return Status
*/
void socketServerClose(void)
{
int fds[MAX_CLIENTS], idx=0;
socketServerGetClientFds(fds, MAX_CLIENTS);
while(socketServerGetNumClients() > 1)
{
printf("socketSeverClose: Closing socket fd:%d\n", fds[idx]);
deleteSocketRec( fds[idx++] );
}
//Now remove the listening socket
if(fds[0])
{
printf("socketSeverClose: Closing the listening socket.");
close(fds[0]);
}
}
<file_sep>/tcp_server_example/main.c
#include <stdio.h>
#include <unistd.h>
#include "app_tcp_server.h"
#include "socket_server.h"
int main(int argc, char *argv[])
{
app_tcp_init(); //初始化tcp服务程序
while(1)
{
sleep(1);
}
app_tcp_destroy(); //释放tcp服务程序
return 0;
}
<file_sep>/tcp_server_example/app_tcp_server.h
#ifndef __APP_TCP_SERVER__
#define __APP_TCP_SERVER__
/*TCPServer端口号*/
#define TCP_PORT 10086
#define MAX_MESSAGE_LEN 2048
/*模块初始化*/
extern int app_tcp_init(void);
/*释放资源(调用的pthread_jion)*/
extern void app_tcp_destroy(void);
#endif //__APP_TCP_SERVER__
<file_sep>/README.md
# linux_c_example
Linux C example
<file_sep>/tcp_server_example/app_tcp_server.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <time.h>
#include "app_tcp_server.h"
#include "socket_server.h"
/*TCP线程ID*/
static pthread_t ulAPPTCPThreadID;
static int TCP_isrunning_flag = 0;
/*解析APP发来的JSON请求*/
void parse_app_data(int clientFd, char *request)
{
}
/*TCP已连接回调*/
void server_connectCB(int clientFd)
{
printf("server_connectCB++[%d]\n", clientFd);
}
/*TCP接收数据包回调*/
void server_rxCB(int clientFd) //change by fangye 20180806
{
char buffer[MAX_MESSAGE_LEN] = {0}; //单个json对象最大长度256
int byteToRead = 0;
int buff_index = 0;
int flag = 0; //记录{}标志
int rtn = -1;
char ch = 0; //记录临时字符
rtn = ioctl(clientFd, FIONREAD, &byteToRead);
if (rtn != 0)
{
printf("server_rxCB: Socket error\n");
}
else
{
printf("Socket Recieve %d bytes pakage\n", byteToRead);
}
while (byteToRead) //循环读取数据
{
ch = 0;
read(clientFd, &ch, 1); //读一个字节
if (ch == '{') //遇到json对象
{
flag++;
}
else if (ch == '}' && flag > 0)
{
flag--;
}
if (flag == 0) //若没有遇到json对象或者已读完一个json对象
{
if (buff_index > 8 && buff_index < MAX_MESSAGE_LEN-1) //判断是否有有效数据,json对象长度至少为9bytes才做处理 {"a":"b"}
{
buffer[buff_index++] = ch; //读取数据
parse_app_data(clientFd, buffer); //解析数据
printf("parse object: %s\n", buffer);
memset(buffer, 0, buff_index);
buff_index = 0; //下标清零
}
}
else
{
if (buff_index < MAX_MESSAGE_LEN-1) //json对象超出长度
buffer[buff_index++] = ch; //读取数据
else //丢掉该包超过长度的数据
{
buff_index = 0;
bzero(buffer, sizeof(buffer));
while (flag == 0 || byteToRead == 0)
{
read(clientFd, &ch, 1); //读一个字节
if (ch == '{') //遇到json对象
{
flag++;
}
else if (ch == '}')
{
flag--;
}
byteToRead--;
}
}
}
byteToRead--;
}
return;
}
/*初始化TCPServer*/
void ServerInit(void)
{
if (socketServerInit(TCP_PORT) == -1)
{
printf("TCP Server init fail....................");
return;
}
socketServerConfig(server_rxCB, server_connectCB);
}
/*TCPServer处理线程*/
void *AppTcpThread(void* arg)
{
printf("TCP Server thread start ....................");
ServerInit();
while (TCP_isrunning_flag)
{
int numClientFds = socketServerGetNumClients();
//poll on client socket fd's for any activity
if (numClientFds)
{
int pollFdIdx;
int *client_fds = malloc(numClientFds * sizeof(int));
//socket client FD's
struct pollfd *pollFds = malloc((numClientFds * sizeof(struct pollfd)));
if (client_fds && pollFds)
{
//Set the socket file descriptors
socketServerGetClientFds(client_fds, numClientFds);
for (pollFdIdx = 0; pollFdIdx < numClientFds; pollFdIdx++)
{
pollFds[pollFdIdx].fd = client_fds[pollFdIdx];
pollFds[pollFdIdx].events = POLLIN | POLLRDHUP;
}
poll(pollFds, numClientFds, -1);
for (pollFdIdx = 0; pollFdIdx < numClientFds; pollFdIdx++)
{
if ((pollFds[pollFdIdx].revents))
{
socketServerPoll(pollFds[pollFdIdx].fd,
pollFds[pollFdIdx].revents);
}
}
free(client_fds);
free(pollFds);
}
}
}
return NULL;
}
void send_data_to_client(char *data , int len)
{
int numClientFds = socketServerGetNumClients(); //获取客户端个数
int *client_fds = malloc(numClientFds * sizeof(int));
if(client_fds)
{
socketServerGetClientFds(client_fds, numClientFds); //获取客户端文件描述符
int i=0;
for(i=1; i<numClientFds; i++) //不发送给第一个连接
{
socketServerSend(data, len, client_fds[i]); //发送数据到客户端
}
free(client_fds);
client_fds = NULL;
}
}
int app_tcp_init(void)
{
TCP_isrunning_flag = 1;
/*创建TCP线程*/
if (0 != pthread_create(&ulAPPTCPThreadID, NULL, AppTcpThread, NULL))
{
printf("Create APPTCPThread failed!");
return -1;
}
return 0;
}
void app_tcp_destroy(void)
{
/*等待线程退出*/
TCP_isrunning_flag = 0;
if (ulAPPTCPThreadID != 0)
{
pthread_cancel(ulAPPTCPThreadID); //解决线程阻塞导致无法回收问题
pthread_join(ulAPPTCPThreadID, NULL);
}
}
<file_sep>/tcp_server_example/Makefile
TARGET := tcp_server
INCLUDE:= -I ./include
LIBS:= -L ./ -lpthread
CSRCS := $(wildcard *.c)
OBJS := $(patsubst %.c, %.o, $(CSRCS))
$(TARGET): $(OBJS)
gcc $+ -o $@ $(LIBS)
%.o:%.c
gcc -c -g $< -o $@ $(INCLUDE)
clean:
rm -rf $(OBJS) $(TARGET)
|
6e464c9b7a25766cb154f8981418d03ea8aac7f5
|
[
"Markdown",
"C",
"Makefile"
] | 7
|
C
|
fangye945a/linux_c_example
|
ee7420f57782dadd9e19ae7ea5c28197c3764290
|
5fd5d5f4dc1c8cfb49b2891d57fbec5746431d14
|
refs/heads/master
|
<file_sep>#
# Genoa - sample initialisation file
#
[GA]
#===
# Initial population - Random / Load / Seed
init.method: R
init.filename: seed.txt
# Run parameters
run.search: True
run.max_generations: 100
run.population_size: 300
;run.nreplace: 50
run.nreplace_percent: 20
run.adapt_interval: 0.1
run.adapt_scale: 0.1
;run.random_seed: 15081947
run.validate: True
# Selection - Crowd / Roulette
select.method: C
select.crowd_factor: 4
# Fitness scaling - Eval / Linear
scale.method: E
scale.eval_min: 1.0
scale.linear_min: 10.0
scale.linear_max: 100.0
scale.linear_decr: 1.0
# Logging
log.all.interval: 200
log.all.filename_prefix: pop
log.best.filename: best.log
log.progress.filename: progress.log
log.progress.show: True
[FloatIndividual]
#================
# Gene definition
fi.num_genes: 4
fi.common_ranges: True
fi.range_low: -20.0
fi.range_high: 20.0
fi.range_filename: ranges.txt
# Operator parameters
fi.nonuniform_mutation_beta: 3.0
fi.creep_mutation_beta: 0.01
# Operator selection weights - at start & end of run
# varied using run.adapt_interval & run.adapt_scale
fi.randomize_mutation: 0.0 0.0
fi.uniform_mutation: 0.3 0.3
fi.nonuniform_mutation: 0.3 0.3
fi.boundary_mutation: 0.3 0.3
fi.creep_mutation: 0.3 0.3
fi.single_xover: 0.3 0.1
fi.double_xover: 0.3 0.1
fi.npoint_xover: 0.3 0.1
fi.single_arith_xover: 0.3 0.1
fi.npoint_arith_xover: 0.3 0.1
fi.whole_arith_xover: 0.3 0.1
[OrderedIndividual]
# =================
# Gene definition
;osi.num_genes: $(Task:tsp.path_length)
osi.num_genes: 0
osi.range_low: 0
# Operator parameters
osi.cyclic_path: True
# Operator selection weights - at start & end of run
# varied using run.adapt_interval & run.adapt_scale
osi.randomize_mutation: 0.0 0.0
osi.position_mutation: 0.5 1.0
osi.order_mutation: 0.5 1.0
osi.scramble_mutation: 0.5 1.0
osi.reverse_mutation: 0.5 1.0
osi.position_xover: 1.0 0.5
osi.order_xover: 1.0 0.5
osi.edge_recombination_xover: 1.0 1.0
[Task]
#=====
eqn.a0: -10
eqn.a1: -1.5
eqn.a2: +0.3
eqn.a3: -0.9
tsp.datafile: ./samples/wi29.tsp
tsp.path_length: 28
<file_sep>#
# genoa.py
# --------
# Copyright (c) 2017 <NAME>. Available under the MIT License
#
# Implementation of a generic genetic algorithm
#
import csv
import datetime
import random
import statistics
import bisect
import sys
from configparser import ConfigParser, ExtendedInterpolation
from individual import Individual
from operators import GAError, OperatorManager
# Sections in the configuration file
SECTION_GA = 'GA'
# GA Parameters
INIT_RANDOM = 'R'
INIT_LOAD = 'L'
INIT_SEEDED = 'S'
SELECT_CROWD = 'C'
SELECT_ROULETTE = 'R'
SCALE_EVALUATED = 'E'
SCALE_LINEAR = 'L'
class GAParameters:
def __init__(self, cfp):
# population initialisation - Random / Seeded
self.init_method = cfp.get(SECTION_GA, 'init.method',
fallback=INIT_RANDOM).upper()
self.init_filename = cfp.get(SECTION_GA, 'init.filename',
fallback='indiv.txt')
# run specific parameters / flags
self.search = cfp.getboolean(SECTION_GA, 'run.search',
fallback=True)
self.max_generations = cfp.getint(SECTION_GA, 'run.max_generations',
fallback=300)
self.pop_size = cfp.getint(SECTION_GA, 'run.population_size',
fallback=50)
self.validate = cfp.getboolean(SECTION_GA, 'run.validate',
fallback=True)
self.nreplace_percent = cfp.getfloat(SECTION_GA,
'run.nreplace_percent',
fallback=-1.0)
if 0 < self.nreplace_percent < 100:
self.nreplace = int(self.pop_size * self.nreplace_percent / 100.0)
else:
self.nreplace = cfp.getint(SECTION_GA, 'run.nreplace',
fallback=10)
self.adapt_interval = cfp.getfloat(SECTION_GA, 'run.adapt_interval',
fallback=0.1)
self.adapt_scale = cfp.getfloat(SECTION_GA, 'run.adapt_scale',
fallback=0.1)
self.random_seed = cfp.get(SECTION_GA, 'run.random_seed',
fallback=None)
# parent selection method - Crowd / Roulette
self.select_method = cfp.get(SECTION_GA, 'select.method',
fallback=SELECT_CROWD).upper()
self.crowd_factor = cfp.getint(SECTION_GA, 'select.crowd_factor',
fallback=4)
# fitness scaling method - Evaluated / Linear
self.scale_method = cfp.get(SECTION_GA, 'scale.method',
fallback=SCALE_EVALUATED).upper()
self.eval_min = cfp.getfloat(SECTION_GA, 'scale.eval_min',
fallback=1.0)
self.linear_min = cfp.getfloat(SECTION_GA, 'scale.linear_min',
fallback=10.0)
self.linear_max = cfp.getfloat(SECTION_GA, 'scale.linear_max',
fallback=100.0)
self.linear_decr = cfp.getfloat(SECTION_GA, 'scale.linear_decr',
fallback=1.0)
# individual logging method - All / Best
self.log_all_interval = cfp.getint(SECTION_GA, 'log.all.interval',
fallback=100)
self.log_all_prefix = cfp.get(SECTION_GA, 'log.all.filename_prefix',
fallback='pop')
self.log_best_filename = cfp.get(SECTION_GA, 'log.best.filename',
fallback='best.log')
self.show_progress = cfp.getboolean(SECTION_GA, 'log.progress.show',
fallback=True)
self.progress_filename = cfp.get(SECTION_GA, 'log.progress.filename',
fallback='progress.log')
# check parameters
if self.init_method not in [INIT_RANDOM, INIT_LOAD, INIT_SEEDED]:
raise GAError('INI file: Valid init.method = [R, L, S]')
if self.select_method not in [SELECT_CROWD, SELECT_ROULETTE]:
raise GAError('INI file: Valid select.method = [C, R]')
if self.crowd_factor <= 0:
self.crowd_factor = 4
if self.scale_method not in [SCALE_EVALUATED, SCALE_LINEAR]:
raise GAError('INI file: Valid scale.method = [E, L]')
if self.log_all_interval <= 0:
self.log_all_interval = 100
if self.pop_size <= 0:
raise GAError('INI file: Population size is <= 0')
class GALogger:
def __init__(self, dumpfile_prefix, best_filename, progress_filename,
show_progress):
self.tstamp = datetime.datetime.now()
self.dumpfile_prefix = dumpfile_prefix
# open file to log the best individual
self.fh_best = open(best_filename, 'wt')
# log performance statistics
self.show_progress = show_progress
self.fh_progress = open(progress_filename, 'w', newline='')
self.csv = csv.writer(self.fh_progress)
self.csv.writerow(['generation', 'timetaken',
'fmax', 'fmin', 'favg', 'fstd',
'operator', 'f1', 'f2', 'f3', 'f4', 'f5'])
def log_best(self, goat):
goat.write(self.fh_best)
def log_all(self, generation, population):
fname = '{:s}_{:04d}.log'.format(self.dumpfile_prefix, generation)
Individual.save_population(fname, population)
def log_progress(self, generation, fitlist, goat):
fmin = min(fitlist)
fmax = max(fitlist)
favg = statistics.mean(fitlist)
fstd = statistics.stdev(fitlist)
# time taken per generation in millisec
tnow = datetime.datetime.now()
diff = (tnow - self.tstamp).total_seconds() * 1000.0
self.tstamp = tnow
self.csv.writerow(round(x, 2) if type(x) == float else x for x in
[generation, diff, fmax, fmin, favg, fstd,
goat.operator, goat.f1, goat.f2, goat.f3, goat.f4,
goat.f5])
# show progress on stderr?
if not self.show_progress:
return
s1 = 'Gen {:d} Best: {:s} F1-5: {:.3f} {:.3f} {:.3f} {:.3f}' \
'{:.3f}\n'.format(generation, goat.operator, goat.f1,
goat.f2, goat.f3, goat.f4, goat.f5)
s2 = 'Fitness: Max/Min: {:.3f} / {:.3f} ' \
'Avg/SD: {:.3f} / {:.3f}\n'.format(fmax, fmin, favg, fstd)
print(s1, s2, file=sys.stderr)
def shutdown(self):
self.fh_best.close()
self.fh_progress.close()
class GeneticAlgorithm:
def __init__(self, configparser, indivclass, objective_func,
eval_mode=False):
# load parameters from configuration file
self._params = GAParameters(configparser)
random.seed(self._params.random_seed)
# Individual class - initialise prototype
if not issubclass(indivclass, Individual):
raise GAError('GA init: incompatible class for Individual')
self._indivclass = indivclass
self._prototype = indivclass(configparser)
# override INI file search mode?
if eval_mode:
self._search = False
self._max_generations = 1
else:
self._search = self._params.search
self._max_generations = self._params.max_generations
# population
self._generation = 0
self._population = []
self._progeny = []
self._objective_func = objective_func
# reproduction - parent selection
self._op_manager = OperatorManager(self._params.adapt_interval,
self._params.adapt_scale)
indivclass.register_operators(self._op_manager, configparser)
self._roulette = [0.0] * self._params.pop_size
# set up scaling/selection functions to be called
if self._params.scale_method == SCALE_EVALUATED:
self._scale_fitness = self._scale_evaluated
else:
self._scale_fitness = self._scale_linear
if self._params.select_method == SELECT_CROWD:
self._select_parent = self._select_from_crowd
else:
self._select_parent = self._select_by_roulette
# variables for statistics
self._sorted_order = []
self._goat = indivclass(self._prototype) # Greatest of all time
# set up logger
self._logger = GALogger(self._params.log_all_prefix,
self._params.log_best_filename,
self._params.progress_filename,
self._params.show_progress)
def initialise(self):
# create the population from the defined prototype
self._population = [self._indivclass(self._prototype)
for _ in range(self._params.pop_size)]
self._progeny = [self._indivclass(self._prototype)
for _ in range(self._params.nreplace + 1)]
# initialise the population
if self._params.init_method == INIT_RANDOM:
for x in self._population:
x.randomize()
else:
# read from file
n, _ = self._indivclass.load_population(self._params.init_filename,
self._population)
# seeded population? randomize the rest
if n < self._params.pop_size:
if self._params.init_method == INIT_LOAD:
raise GAError('GA load: insufficent individuals in file')
elif self._params.init_method == INIT_SEEDED:
for i in range(n, self._params.pop_size):
self._population[i].randomize()
self.reset_population()
def iterate(self):
if self._generation > self._max_generations:
raise GAError('GA iterate: max generations exceeded')
# evaluate new individuals from previous generation
self._evaluate_new()
# generate and log statistics
self._calculate_stats()
self._scale_fitness()
# reproduce?
if self._params.search:
self._reproduce()
# finished the run?
self._generation += 1
finished = (self._generation > self._max_generations)
if finished:
# all clean up procedures
self._logger.shutdown()
return not finished
def reset_population(self):
for x in self._population:
x.reset()
def best_individual(self):
return self._goat
def current_generation(self):
return self._generation
def _update_roulette(self):
# Normalize & create a cumulative distribution on the population
# based on the adjusted fitness.
total = sum(x.adj_fitness for x in self._population)
self._roulette[0] = self._population[0].adj_fitness / total
for i in range(1, self._params.pop_size):
self._roulette[i] = self._roulette[i - 1] \
+ (self._population[i].adj_fitness / total)
# Parent selection methods
def _select_by_roulette(self):
# probability of selection = f(adj_fitness)
i = bisect.bisect_left(self._roulette, random.random())
return self._population[i]
def _select_from_crowd(self):
# select the best adj_fitness in a random crowd
b = self._population[random.randrange(self._params.pop_size)]
for _ in range(1, self._params.crowd_factor):
x = self._population[random.randrange(self._params.pop_size)]
if x.adj_fitness > b.adj_fitness:
b = x
return b
# produce the next generation and replace worst in current
def _reproduce(self):
# get sorted order & scale fitness
if self._params.select_method == SELECT_ROULETTE:
self._update_roulette()
# normalise operator picking probablities based on generation no.
epoch = self._generation / self._max_generations
self._op_manager.rescale_probabilities(epoch)
# parameters (if) needed by genetic operators
args = dict(epoch=epoch)
# produce progeny
n = 0
while n < self._params.nreplace:
op = self._op_manager.choose()
# choose parents
parents = [self._select_parent() for _ in range(op.num_parents)]
# next free slots of progeny
children = []
for i in range(op.num_children):
children.append(self._progeny[n])
children[i].operator = op.name
n += 1
# apply the genetic operator
op.procreate(parents, children, args)
# replace worst
for i in range(self._params.nreplace):
w = self._sorted_order[i]
self._progeny[i].copyto(self._population[w])
self._population[w].reset()
# Utility functions
def _evaluate_new(self):
# call objective function for new individuals
for x in self._population:
if x.changed:
if self._params.validate and not x.valid():
raise GAError('GA validate: validation failed')
self._objective_func(x)
x.changed = False
# Population statistics & logging
def _calculate_stats(self):
# collect (fitness, index) for population
ranking = [(x.fitness, i) for i, x in enumerate(self._population)]
# rank in ascending fitness
self._sorted_order = [t[1] for t in sorted(ranking)]
flist = [t[0] for t in ranking]
best_idx = self._sorted_order[-1]
# keep a copy of the best individual across all generations
if not self._population[best_idx].equal(self._goat):
self._population[best_idx].copyto(self._goat)
self._logger.log_best(self._goat)
# log entire population
if (self._generation % self._params.log_all_interval == 0) \
or (self._generation == self._max_generations):
self._logger.log_all(self._generation, self._population)
# show stats for this generation
self._logger.log_progress(self._generation, flist, self._goat)
# Methods to scale fitness to adj_fitness
def _scale_evaluated(self):
min_fitness = self._population[self._sorted_order[0]].fitness
for x in self._population:
x.adj_fitness = x.fitness - min_fitness + self._params.eval_min
def _scale_linear(self):
wt = 0
for i in reversed(self._sorted_order):
self._population[i].adj_fitness = \
max(self._params.linear_max - (wt * self._params.linear_decr),
self._params.linear_min)
wt += 1
#
# Utility functions
# -----------------
def load_config_parser(filename):
cfg = ConfigParser(interpolation=ExtendedInterpolation())
cfg.read(filename)
return cfg
<file_sep>#
# individual.py
# -------------
# Copyright (c) 2017 <NAME>. Available under the MIT License
#
import random
from abc import ABCMeta, abstractmethod
from collections import defaultdict
from configparser import ConfigParser
from operators import GAError, GeneticOperator
# Sections in the configuration file
SECTION_FI = 'FloatIndividual'
SECTION_OSI = 'OrderedIndividual'
# String representation
NO_OPERATOR = 'RAmu'
START_OF_GENE = 'C:'
FI_GENES_PER_LINE = 5
OSI_GENES_PER_LINE = 20
class Individual(metaclass=ABCMeta):
"""Abstract Base Class for Genetic Algorithm individuals."""
def __init__(self, details):
self.operator = NO_OPERATOR
self.changed = True
self.fitness = self.adj_fitness = 0.0
self.f1 = self.f2 = self.f3 = self.f4 = self.f5 = 0.0
# Individuals are created from a prototype instance.
# The prototype is initially configured by user-defined parameters
# specified in a config file or as parameters passed in a dict
if not isinstance(details, (ConfigParser, Individual, dict)):
raise GAError('Individual init: incompatible blueprint')
def reset(self):
self.changed = True
self.fitness = 0.0
def copyto(self, other):
if other is self:
return
if not isinstance(other, Individual):
raise GAError('Individual copy: incompatible class')
other.changed = self.changed
other.fitness = self.fitness
other.adj_fitness = self.adj_fitness
other.operator = self.operator
other.f1 = self.f1
other.f2 = self.f2
other.f3 = self.f3
other.f4 = self.f4
other.f5 = self.f5
def read(self, fh):
# return False on EOF
s = fh.readline().strip()
if not s:
return False
flds = s.split()
if len(flds) != 9:
raise GAError('Individual read: insufficient fields; expected 8')
if flds[0] != START_OF_GENE:
raise GAError('Individual read: start of gene marker not found')
self.fitness = float(flds[1])
self.operator = flds[2]
self.adj_fitness = float(flds[3])
self.f1 = float(flds[4])
self.f2 = float(flds[5])
self.f3 = float(flds[6])
self.f4 = float(flds[7])
self.f5 = float(flds[8])
return True
def write(self, fh):
print(self, file=fh)
print(file=fh)
def __repr__(self):
s1 = '{:s} {:0.4f} {:4s} {:0.4f}'. \
format(START_OF_GENE, self.fitness, self.operator,
self.adj_fitness)
s2 = ' {:0.4f} {:0.4f} {:0.4f} {:0.4f} {:0.4f}'. \
format(self.f1, self.f2, self.f3, self.f4, self.f5)
return s1 + s2
@abstractmethod
def randomize(self):
pass
@abstractmethod
def equal(self, other):
pass
@abstractmethod
def valid(self):
pass
@abstractmethod
def chromosome(self):
pass
@classmethod
def get_attributes(cls):
"""Return a dictionary with required creation parameters."""
raise GAError('Individual: get_attributes() undefined in {0}'
.format(cls))
@classmethod
def load_population(cls, filename, plist, attributes=None):
"""Load individuals from a given file.
plist - a list of Individual instances compatible with the file being
read. The file is read into these instances. If None, new instances
are created using 'attributes'
attributes - dict (as returned by get_attributes() with updated values)
"""
# read into the given list
n = 0
if plist is not None:
if not (isinstance(plist, list)
and len(plist) > 0
and all(isinstance(x, cls) for x in plist)):
raise GAError('Individual: load_population() bad plist')
with open(filename, 'rt') as fh:
while n < len(plist):
if not plist[n].read(fh):
break
n += 1
else:
# create a new list and return it
plist = []
with open(filename, "rt") as fh:
while True:
i = cls(attributes)
if not i.read(fh):
break
n += 1
plist.append(i)
return n, plist
@classmethod
def save_population(cls, filename, population):
"""Save the population (list of individuals) to the given file."""
with open(filename, "wt") as fh:
for x in population:
x.write(fh)
@classmethod
def register_operators(cls, op_manager, configparser):
raise GAError('Individual: register_operators() undefined in {0}'
.format(cls))
@staticmethod
def _parse_probabilities(s):
if s is None or s.strip == '':
return 0.0, 0.0
flds = s.split()
if len(flds) == 1:
a = float(flds[0])
return a, a
return float(flds[0]), float(flds[1])
class FloatIndividual(Individual):
"""Individual whose genes are represented as floats"""
def __init__(self, details):
super().__init__(details)
self.num_genes = 0
self.genes = None
self.minval = None
self.maxval = None
# configure based on prototype
if isinstance(details, FloatIndividual):
self.num_genes = details.num_genes
# share the prototype's ranges - or make a copy?
self.minval = details.minval
self.maxval = details.maxval
# fetch parameters from the config file and build prototype
elif isinstance(details, ConfigParser):
self.num_genes = details.getint(SECTION_FI, 'fi.num_genes',
fallback=0)
if self.num_genes <= 2:
raise GAError('FloatIndividual init: num genes <= 2')
# range for each gene
common_ranges = details.getboolean(SECTION_FI, 'fi.common_ranges',
fallback=True)
rlow = details.getfloat(SECTION_FI, 'fi.range_low',
fallback=0.0)
rhigh = details.getfloat(SECTION_FI, 'fi.range_high',
fallback=0.0)
rfilename = details.get(SECTION_FI, 'fi.range_filename',
fallback=None)
self.minval = [rlow] * self.num_genes
self.maxval = [rhigh] * self.num_genes
if common_ranges:
# check common range for each gene
if rlow >= rhigh:
raise GAError('FloatIndividual init: range low >= high')
else:
# specific range for each gene defined in given file
with open(rfilename) as fh:
for i in range(self.num_genes):
# format assumed "low high"
flds = fh.readline().strip().split()
if len(flds) != 2:
raise GAError(
'FloatIndividual init: bad range file')
if flds[0] >= flds[1]:
raise GAError(
'FloatIndividual init: range low >= high')
self.minval[i] = float(flds[0])
self.maxval[i] = float(flds[1])
# dictionary with parameters
elif isinstance(details, dict):
self.num_genes = details['fi.num_genes']
if self.num_genes <= 2:
raise GAError('FloatIndividual init: num genes <= 2')
# range for each gene
rlow = details['fi.range_low']
rhigh = details['fi.range_high']
if rlow >= rhigh:
raise GAError('FloatIndividual init: range low >= high')
self.minval = [rlow] * self.num_genes
self.maxval = [rhigh] * self.num_genes
# ooops!
else:
raise GAError('FloatIndividual init: cannot initialise')
# create a null genotype
self.genes = [0.0] * self.num_genes
def copyto(self, other):
if other is self:
return
if not isinstance(other, FloatIndividual):
raise GAError('FloatIndividual copy: incompatible object class')
super().copyto(other)
other.num_genes = self.num_genes
other.genes = self.genes.copy()
def read(self, fh):
if not super().read(fh):
return False
# parse genes - same as str representation
flds = []
for i in range(self.num_genes):
if (i % FI_GENES_PER_LINE) == 0:
s = fh.readline().strip()
if not s:
raise GAError('FloatIndividual read: unexpected EOF')
flds = s.split()
self.genes[i] = float(flds.pop(0))
# read a blank line separating each individual
s = fh.readline().strip()
if s != '':
raise GAError('FloatIndividual read: expected blank line missing')
return True
def __repr__(self):
s1 = super().__repr__()
s2 = ''
i = 0
while i < self.num_genes:
s2 += ' {:13.6E}'.format(self.genes[i])
i += 1
if (i < self.num_genes) and (i % FI_GENES_PER_LINE) == 0:
s2 += '\n'
return s1 + '\n' + s2
def randomize(self):
for i in range(self.num_genes):
self.genes[i] = random.uniform(self.minval[i], self.maxval[i])
def equal(self, other):
return self.genes == other.genes
def valid(self):
# all genes in valid range? otherwise dump to stderr?
for i in range(self.num_genes):
if not (self.minval[i] <= self.genes[i] <= self.maxval[i]):
return False
return True
def chromosome(self):
# return gene (or a copy?)
return self.genes
@classmethod
def get_attributes(cls):
return {'fi.num_genes': 0, 'fi.range_low': 0.0, 'fi.range_high': 0.0}
# Genetic operators
@classmethod
def register_operators(cls, op_manager, cfp):
# Mutation operators
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_FI, 'fi.randomize_mutation', fallback=None))
op_manager.register(GeneticOperator('RAmu', cls._randomize_mutation,
1, 1, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_FI, 'fi.uniform_mutation', fallback=None))
op_manager.register(GeneticOperator('UFmu', cls._uniform_mutation,
1, 1, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_FI, 'fi.nonuniform_mutation', fallback=None))
beta = cfp.getfloat(SECTION_FI, 'fi.nonuniform_mutation_beta',
fallback=3.0)
op_manager.register(GeneticOperator('NUmu', cls._nonuniform_mutation,
1, 1, p1, p2, dict(beta=beta)))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_FI, 'fi.boundary_mutation', fallback=None))
op_manager.register(GeneticOperator('BOmu', cls._boundary_mutation,
1, 1, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_FI, 'fi.creep_mutation', fallback=None))
beta = cfp.getfloat(SECTION_FI, 'fi.creep_mutation_beta',
fallback=0.01)
op_manager.register(GeneticOperator('CRmu', cls._creep_mutation,
1, 1, p1, p2, dict(beta=beta)))
# Crossover operators
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_FI, 'fi.single_xover', fallback=None))
op_manager.register(GeneticOperator('SIxo', cls._single_xover,
2, 2, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_FI, 'fi.double_xover', fallback=None))
op_manager.register(GeneticOperator('DOxo', cls._double_xover,
2, 2, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_FI, 'fi.npoint_xover', fallback=None))
op_manager.register(GeneticOperator('NPxo', cls._npoint_xover,
2, 2, p1, p2))
# Arithmetic crossover operators
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_FI, 'fi.single_arith_xover', fallback=None))
op_manager.register(GeneticOperator('SIax', cls._single_arith_xover,
2, 2, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_FI, 'fi.npoint_arith_xover', fallback=None))
op_manager.register(GeneticOperator('NPax', cls._npoint_arith_xover,
2, 2, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_FI, 'fi.whole_arith_xover', fallback=None))
op_manager.register(GeneticOperator('WHax', cls._whole_arith_xover,
2, 2, p1, p2))
@staticmethod
def _randomize_mutation(parents, children, _args):
"""Randomize all genes - useful as a null hypothesis."""
p1 = parents[0]
c1 = children[0]
c1.genes = p1.genes.copy()
c1.randomize()
@staticmethod
def _uniform_mutation(parents, children, _args):
"""Mutate a random gene to a random value."""
p1 = parents[0]
c1 = children[0]
c1.genes = p1.genes.copy()
w = random.randrange(c1.num_genes)
c1.genes[w] = random.uniform(c1.minval[w], c1.maxval[w])
@staticmethod
def _nonuniform_mutation(parents, children, args):
"""Mutate a random gene to a non-uniform random value."""
p1 = parents[0]
c1 = children[0]
c1.genes = p1.genes.copy()
w = random.randrange(c1.num_genes)
epoch = args['epoch']
beta = args['beta']
delta = random.random() ** ((1.0 - epoch) ** beta)
delta = (c1.maxval[w] - c1.minval[w]) * (1.0 - delta)
c1.genes[w] += delta if random.random() < 0.5 else -delta
# fix if gene has breached the valid range
c1.genes[w] = min(max(c1.minval[w], c1.genes[w]), c1.maxval[w])
@staticmethod
def _boundary_mutation(parents, children, _args):
"""Mutate a random gene to within a decile of a bondary value"""
p1 = parents[0]
c1 = children[0]
c1.genes = p1.genes.copy()
w = random.randrange(c1.num_genes)
rng = (c1.maxval[w] - c1.minval[w]) / 10.0
if random.random() < 0.5:
c1.genes[w] = random.uniform(c1.minval[w], c1.minval[w] + rng)
else:
c1.genes[w] = random.uniform(c1.maxval[w] - rng, c1.maxval[w])
@staticmethod
def _creep_mutation(parents, children, args):
"""Mutate a random number of genes by perturbing them slightly."""
p1 = parents[0]
c1 = children[0]
c1.genes = p1.genes.copy()
# perturb genes by a creep factor
gamma = 1.0 + args['beta']
prob = random.uniform(0.25, 0.5)
for i in range(c1.num_genes):
if random.random() > prob:
continue
if random.random() < 0.5:
c1.genes[i] *= gamma
else:
c1.genes[i] /= gamma
# fix if gene has breached the valid range
c1.genes[i] = min(max(c1.minval[i], c1.genes[i]), c1.maxval[i])
@staticmethod
def _single_xover(parents, children, _args):
"""Crossover at a single point."""
p1 = parents[0]
p2 = parents[1]
c1 = children[0]
c2 = children[1]
c1.genes = p1.genes.copy()
c2.genes = p2.genes.copy()
# potential error if num genes is less than 2
if p1.num_genes < 2:
return
# crossover at an arbitrary point
w = random.randrange(1, c1.num_genes)
for i in range(w, c1.num_genes):
c1.genes[i] = p2.genes[i]
c2.genes[i] = p1.genes[i]
@staticmethod
def _double_xover(parents, children, _args):
"""Crossover of a random section"""
p1 = parents[0]
p2 = parents[1]
c1 = children[0]
c2 = children[1]
c1.genes = p1.genes.copy()
c2.genes = p2.genes.copy()
# potential error if num genes is less than 3
if p1.num_genes < 3:
return
# crossover of a random section
w1 = random.randrange(1, c1.num_genes - 1)
w2 = random.randrange(w1 + 1, c1.num_genes)
for i in range(w1, w2):
c1.genes[i] = p2.genes[i]
c2.genes[i] = p1.genes[i]
@staticmethod
def _npoint_xover(parents, children, _args):
"""Crossover with each gene coming from either parent."""
p1 = parents[0]
p2 = parents[1]
c1 = children[0]
c2 = children[1]
c1.genes = p1.genes.copy()
c2.genes = p2.genes.copy()
# crossover of multiple random sections
for i in range(1, c1.num_genes):
if random.random() >= 0.5:
c1.genes[i] = p2.genes[i]
c2.genes[i] = p1.genes[i]
@staticmethod
def _single_arith_xover(parents, children, _args):
"""Arithmetic crossover (mix) of a random gene from two parents."""
p1 = parents[0]
p2 = parents[1]
c1 = children[0]
c2 = children[1]
c1.genes = p1.genes.copy()
c2.genes = p2.genes.copy()
# mix a random gene... how is this different from a mutation?
w = random.randrange(c1.num_genes)
if c1.genes[w] == c2.genes[w]:
return
x = random.random()
y = 1.0 - x
c1.genes[w] = x * p1.genes[w] + y * p2.genes[w]
c2.genes[w] = x * p2.genes[w] + y * p1.genes[w]
@staticmethod
def _npoint_arith_xover(parents, children, _args):
"""Arithmetic crossover (mix) of multiple genes in different
proportions.
"""
p1 = parents[0]
p2 = parents[1]
c1 = children[0]
c2 = children[1]
c1.genes = p1.genes.copy()
c2.genes = p2.genes.copy()
# some genes mixed in random ratios
for i in range(c1.num_genes):
if random.random() >= 0.5:
x = random.random()
y = 1.0 - x
c1.genes[i] = x * p1.genes[i] + y * p2.genes[i]
c2.genes[i] = x * p2.genes[i] + y * p1.genes[i]
@staticmethod
def _whole_arith_xover(parents, children, _args):
"""Arithmetic crossover (mix) of all genes in the same proportion."""
p1 = parents[0]
p2 = parents[1]
c1 = children[0]
c2 = children[1]
c1.genes = p1.genes.copy()
c2.genes = p2.genes.copy()
# all genes mixed in the same random ratio
x = random.random()
y = 1.0 - x
for i in range(c1.num_genes):
c1.genes[i] = x * p1.genes[i] + y * p2.genes[i]
c2.genes[i] = x * p2.genes[i] + y * p1.genes[i]
class OrderedIndividual(Individual):
"""Individual whose genes form an ordered set"""
def __init__(self, details):
super().__init__(details)
self.num_genes = 0
self.genes = None
self.range_low = 0
# configure based on prototype
if isinstance(details, OrderedIndividual):
self.num_genes = details.num_genes
self.range_low = details.range_low
# fetch parameters from the config file and build prototype
elif isinstance(details, ConfigParser):
self.num_genes = details.getint(SECTION_OSI, 'osi.num_genes',
fallback=0)
if self.num_genes <= 2:
raise GAError('OrderedIndividual init: num genes <= 2')
self.range_low = details.getint(SECTION_OSI, 'osi.range_low',
fallback=0)
# dictionary with parameters
elif isinstance(details, dict):
self.num_genes = details['osi.num_genes']
if self.num_genes <= 2:
raise GAError('OrderedIndividual init: num genes <= 2')
self.range_low = details.get('osi.range_low', 0)
# ooops!
else:
raise GAError('OrderedIndividual init: cannot initialise')
# create a null genotype
self.genes = list(range(self.range_low,
self.range_low + self.num_genes))
def copyto(self, other):
if other is self:
return
if not isinstance(other, OrderedIndividual):
raise GAError('OrderedIndividual copy: incompatible object class')
super().copyto(other)
other.num_genes = self.num_genes
other.genes = self.genes.copy()
def read(self, fh):
if not super().read(fh):
return False
# parse genes - same as str representation
flds = []
for i in range(self.num_genes):
if (i % OSI_GENES_PER_LINE) == 0:
s = fh.readline().strip()
if not s:
raise GAError('OrderedIndividual read: unexpected EOF')
flds = s.split()
self.genes[i] = int(flds.pop(0))
# read a blank line separating each individual
s = fh.readline().strip()
if s != '':
raise GAError(
'OrderedIndividual read: expected blank line missing')
return True
def __repr__(self):
s1 = super().__repr__()
s2 = ''
i = 0
while i < self.num_genes:
s2 += ' {:3d}'.format(self.genes[i])
i += 1
if (i < self.num_genes) and (i % OSI_GENES_PER_LINE) == 0:
s2 += '\n'
return s1 + '\n' + s2
def randomize(self):
random.shuffle(self.genes)
def equal(self, other):
return self.genes == other.genes
def valid(self):
s = set(self.genes)
if (min(s) == self.range_low) and (len(s) == self.num_genes):
return True
return False
def chromosome(self):
# return gene (or a copy?)
return self.genes
@classmethod
def get_attributes(cls):
return {'osi.num_genes': 0, 'osi.range_low': 0}
# Genetic operators
@classmethod
def register_operators(cls, op_manager, cfp):
# Mutation operators
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_OSI, 'osi.randomize_mutation', fallback=None))
op_manager.register(GeneticOperator('RAmu', cls._randomize_mutation,
1, 1, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_OSI, 'osi.position_mutation', fallback=None))
op_manager.register(GeneticOperator('POmu', cls._position_mutation,
1, 1, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_OSI, 'osi.order_mutation', fallback=None))
op_manager.register(GeneticOperator('ORmu', cls._order_mutation,
1, 1, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_OSI, 'osi.scramble_mutation', fallback=None))
op_manager.register(GeneticOperator('SCmu', cls._scramble_mutation,
1, 1, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_OSI, 'osi.reverse_mutation', fallback=None))
op_manager.register(GeneticOperator('RVmu', cls._reverse_mutation,
1, 1, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_OSI, 'osi.position_xover', fallback=None))
op_manager.register(GeneticOperator('POxo', cls._position_xover,
2, 2, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_OSI, 'osi.order_xover', fallback=None))
op_manager.register(GeneticOperator('ORxo', cls._order_xover,
2, 2, p1, p2))
p1, p2 = cls._parse_probabilities(
cfp.get(SECTION_OSI, 'osi.edge_recombination_xover',
fallback=None))
cyclic = cfp.getboolean(SECTION_OSI, 'osi.cyclic_path',
fallback=True)
op_manager.register(GeneticOperator('ERxo',
cls._edge_recombination_xover,
2, 2, p1, p2, dict(cyclic=cyclic)))
@staticmethod
def _randomize_mutation(parents, children, _args):
"""Randomize (shuffle) all genes - useful as a null hypothesis."""
p1 = parents[0]
c1 = children[0]
c1.genes = p1.genes.copy()
c1.randomize()
@staticmethod
def _position_mutation(parents, children, _args):
"""Mutate by moving a random item to a random position.
The order is maintained:
123x456y789 => 123xy456789 or 123456xy789
"""
p1 = parents[0]
c1 = children[0]
c1.genes = p1.genes.copy()
# select two items at random...
w1 = random.randrange(0, c1.num_genes - 1)
w2 = random.randrange(w1 + 1, c1.num_genes)
if random.random() < 0.5:
# ... place the second after the first
# 123x456y789 => 123xy456789
c1.genes.insert(w1 + 1, c1.genes[w2])
del c1.genes[w2 + 1]
else:
# ... or the first before the second
# 123x456y789 => 123456xy789
c1.genes.insert(w2, c1.genes[w1])
del c1.genes[w1]
@staticmethod
def _order_mutation(parents, children, _args):
"""Mutate by switching the order of two items.
The positions are maintained:
123x456y789 => 123y456x789
"""
p1 = parents[0]
c1 = children[0]
c1.genes = p1.genes.copy()
# select two items at random - switch them
w1 = random.randrange(0, c1.num_genes - 1)
w2 = random.randrange(w1 + 1, c1.num_genes)
c1.genes[w1], c1.genes[w2] = c1.genes[w2], c1.genes[w1]
@staticmethod
def _scramble_mutation(parents, children, _args):
"""Mutate by scrambling a section of the chromosome.
123x456y789 => 123x645y789
"""
p1 = parents[0]
c1 = children[0]
c1.genes = p1.genes.copy()
# select two indices at random - scramble the items between them
w1 = random.randrange(0, c1.num_genes - 1)
w2 = random.randrange(w1 + 1, c1.num_genes)
snippet = c1.genes[w1:w2]
random.shuffle(snippet)
c1.genes = c1.genes[:w1] + snippet + c1.genes[w2:]
@staticmethod
def _reverse_mutation(parents, children, _args):
"""Mutate by reversing a section of the chromosome.
123x456y789 => 123x654y789
"""
p1 = parents[0]
c1 = children[0]
c1.genes = p1.genes.copy()
# select two indices at random - reverse the items between them
w1 = random.randrange(0, c1.num_genes - 1)
w2 = random.randrange(w1 + 1, c1.num_genes)
c1.genes = (c1.genes[:w1] + list(reversed(c1.genes[w1:w2]))
+ c1.genes[w2:])
@staticmethod
def _position_xover(parents, children, _args):
"""Crossover maintaining position from each parent
Given
p1 = beagfdc
p2 = agdbfec
m = 1000110
"afe" from p2 is inserted in p1 in the same position. All other items
in p1 are shifted down in original order,
c1 = abgdfec
c2 = bagefdc
"""
p1 = parents[0]
p2 = parents[1]
c1 = children[0]
c2 = children[1]
# create a mask of genes to splice
prob = random.uniform(0.25, 0.5)
mask = [random.random() < prob for _ in range(c1.num_genes)]
c1.genes = _crossover_by_posn(p1.genes, p2.genes, mask)
c2.genes = _crossover_by_posn(p2.genes, p1.genes, mask)
@staticmethod
def _order_xover(parents, children, _args):
"""Crossover maintaining order in each parent.
Given
p1 = beagfdc
p2 = agdbfec
m = 1000110
"afe" from p2 replace "eaf" in p1. All other items maintain their
position,
c1 = bafgedc (afe from p2 inserted in p1)
c2 = agbfdec (bfd from p1 inserted in p2)
"""
p1 = parents[0]
p2 = parents[1]
c1 = children[0]
c2 = children[1]
# create a mask of genes to splice
prob = random.uniform(0.25, 0.5)
mask = [random.random() < prob for _ in range(c1.num_genes)]
c1.genes = _crossover_by_order(p1.genes, p2.genes, mask)
c2.genes = _crossover_by_order(p2.genes, p1.genes, mask)
@staticmethod
def _edge_recombination_xover(parents, children, args):
"""Crossover based on edges i.e. pairs of vertices.
See Wikipedia for more details.
The 'cyclic' flag indicates if there is an edge between the first and
last item.
"""
p1 = parents[0]
p2 = parents[1]
c1 = children[0]
c2 = children[1]
cyclic = args['cyclic']
c1.genes = _edge_recombine(p1.genes, p2.genes, cyclic)
c2.genes = _edge_recombine(p2.genes, p1.genes, cyclic)
#
# helper routines for OrderedIndividual operators
#
def _crossover_by_posn(p1, p2, mask):
g2 = [x for m, x in zip(mask, p2) if m]
g1 = [x for x in p1 if x not in g2]
c = [g2.pop(0) if m else g1.pop(0) for m in mask]
return c
def _crossover_by_order(p1, p2, mask):
g2 = [x for m, x in zip(mask, p2) if m]
gc = g2.copy()
c = [x if x not in g2 else gc.pop(0) for x in p1]
return c
def _insert_in_edgemap(emap, r, cyclic):
n = len(r)
node = r[0]
emap[node].add(r[1])
if cyclic:
emap[node].add(r[-1])
for i in range(1, n - 1):
node = r[i]
emap[node].add(r[i - 1])
emap[node].add(r[i + 1])
node = r[n - 1]
emap[node].add(r[n - 2])
if cyclic:
emap[node].add(r[0])
def _edge_recombine(p1, p2, cyclic):
# cyclic - assume a Hamiltonian cycle with an edge between the
# first and last elements.
# Build the edge map.
emap = defaultdict(set)
_insert_in_edgemap(emap, p1, cyclic)
_insert_in_edgemap(emap, p2, cyclic)
# build new path
v = p1[0]
child = [v]
while len(child) < len(p1):
# remove v from the edge map
for edge in emap.values():
if v in edge:
edge.discard(v)
# order nodes from v by fewest edges
ecount = defaultdict(list)
for x in emap[v]:
ecount[len(emap[x])].append(x)
if len(ecount) > 0:
from_nodes = ecount[sorted(ecount)[0]]
else:
from_nodes = list(set(p1) - set(child))
v = random.choice(from_nodes)
child.append(v)
return child
<file_sep>#
# operators.py
# ------------
# Copyright (c) 2017 <NAME>. Available under the MIT License
#
import bisect
import random
class GAError(Exception):
"""Base class for Genetic Algorithm exceptions."""
def __init__(self, message=''):
self.message = message
super().__init__(self, message)
def __repr__(self):
return self.message
__str__ = __repr__
class GeneticOperator:
"""Common interface for genetic operators implemented in an Individual."""
def __init__(self, name, func, num_parents, num_children,
prob_initial, prob_final, params=None):
self.name = name
self._func = func
self.num_parents = num_parents
self.num_children = num_children
self.prob_initial = prob_initial
self.prob_final = prob_final
self.parameters = params
def procreate(self, parents, children, args):
# combine operator specific parameters with GA specific parameters
combined = args.copy()
if self.parameters is not None:
combined.update(self.parameters)
# ... and call the reproduction function
self._func(parents, children, combined)
class OperatorManager:
"""Manage the random choosing of genetic operators for reproduction.
A cumulative distribution of the probabilities of choosing different
operators is updated every few generations based on adapt_interval and
adapt_scale. This allows certain operators to be more prevalent (or
absent) at different stages of the search.
"""
def __init__(self, adapt_interval, adapt_scale):
self._operators = []
self._cdf = None
self._next_interval = 0.0
self._interval_step = adapt_interval
self._curr_scale = 0.0
self._scale_step = adapt_scale
def register(self, op):
self._operators.append(op)
def rescale_probabilities(self, epoch):
"""Update the probabilities of choosing a particular operator."""
if epoch < self._next_interval:
return
if (self._cdf is None) or (len(self._cdf) != len(self._operators)):
self._cdf = [0.0] * len(self._operators)
if self._curr_scale > 1.0:
self._curr_scale = 1.0
# rescale probabilities for the current interval
p = 1.0 - self._curr_scale
q = self._curr_scale
for i, op in enumerate(self._operators):
self._cdf[i] = (p * op.prob_initial) + (q * op.prob_final)
# normalize
total = sum(self._cdf)
self._cdf[0] /= total
for i in range(1, len(self._cdf)):
self._cdf[i] = self._cdf[i - 1] + self._cdf[i] / total
self._next_interval += self._interval_step
self._curr_scale += self._scale_step
def choose(self):
"""Choose an operator based on current probabilities."""
return self._operators[bisect.bisect_left(self._cdf, random.random())]
<file_sep># genoa
A generic Genetic Algorithm - supports a) float and b) ordered set types of chromosomes
* genoa.py: implements the Genetic Algorithm
* individual.py: implements the individuals (chromosomes)
* operators.py: implements a common interface to genetic operators
* ga.ini: sample initialisation file
|
ade847ef645bd7982d104a0e7d8a484a572d9db8
|
[
"Markdown",
"Python",
"INI"
] | 5
|
INI
|
cdragun/genoa
|
84378a177d676a479aa8cfe21bfa940aff337dae
|
1bd0ebab524327aa262ccbc8fa779f0142a87e19
|
refs/heads/develop
|
<repo_name>studiometa/eslint-config<file_sep>/src/overrides/build-files.js
module.exports = {
files: [
'gulpfile.js',
'webpack.mix.js',
'.*rc.js',
'.*rc.mjs',
'.*rc.cjs',
'*.config.js',
'*.config.mjs',
'*.config.cjs',
],
env: {
node: true,
},
rules: {
'global-require': 'off',
'import/no-extraneous-dependencies': ['warn', { devDependencies: true }],
},
};
<file_sep>/src/legacy.js
module.exports = {
root: true,
extends: [
'eslint:recommended',
'eslint-config-airbnb-base/legacy',
require.resolve('./rules/best-practices.js'),
require.resolve('./rules/possible-errors.js'),
require.resolve('./rules/stylistic-issues.js'),
'plugin:prettier/recommended',
],
};
<file_sep>/test/legacy/index.js
(function iife(window) {
'use strict';
window.addEventListener('load', function onload() {
console.log('hello world');
});
})(window);
<file_sep>/test/build-files/meta.config.mjs
import prettier from 'prettier';
export default {
src: ['./foo.js'],
prettier,
};
<file_sep>/src/resolvers/export-field.js
const path = require('path');
const { resolve: resolveExports } = require('resolve.exports');
const { builtinModules } = require('module');
const builtins = new Set(builtinModules);
/**
* @param {string} source source
* @param {string} file file
* @returns {{ found: boolean, path?: string }}
*/
function resolve(source, file) {
if (builtins.has(source)) {
// return { found: false }; // this also works?
return { found: true, path: null };
}
try {
const moduleId = require.resolve(source, { paths: [path.dirname(file)] });
return { found: true, path: moduleId };
} catch (/** @type {any} */ err) {
if (err.code === 'MODULE_NOT_FOUND' && err.path?.endsWith('/package.json')) {
const { name, module, main, exports } = require(err.path);
const resolved = resolveExports({ name, module, main, exports }, source);
const moduleId = path.join(path.dirname(err.path), resolved);
return { found: true, path: moduleId };
}
return { found: false };
}
}
module.exports = {
interfaceVersion: 2,
resolve,
};
<file_sep>/test/build-files/.eslintrc.js
module.exports = {
root: true,
extends: [require.resolve('../../src/index.js')],
};
<file_sep>/test/build-files/meta.js
import config from '@studiometa/prettier-config';
export default {
src: ['./foo.js'],
config,
};
<file_sep>/test/default/component.js
/**
* Class.
*/
export default class Component {
config = {
name: 'Component',
};
}
<file_sep>/readme.md
# Studio Meta ESLint Configurations
[](https://www.npmjs.com/package/@studiometa/eslint-config)
[](https://david-dm.org/studiometa/eslint-config)
[](https://david-dm.org/studiometa/eslint-config?type=dev)
> Set of [ESLint](https://eslint.org/) configurations for multiple usages.
## Installation
Install the package with NPM:
```bash
npm install --save-dev eslint prettier @studiometa/eslint-config
```
## Usage
To use the basic configuration, you just have to install this package and reference it in your ESLint configuration file:
```js
module.exports = {
extends: '@studiometa/eslint-config',
};
```
If you have a legacy project with ES5 code, you can use the legacy configuration:
```js
module.exports = {
extends: '@studiometa/eslint-config/src/legacy',
};
```
## Rules documentation
Find below some documentation on the rules this configuration extends. Some are best practices, some are more opinionated choices.
### `eslint:recommended`
These rules report common problems we can encounter in JavaScript. The full list can be found in the [ESLint documentation](https://eslint.org/docs/rules/).
### `eslint-config-airbnb-base`
People at Airbnb have written a [detailed documentation](https://github.com/airbnb/javascript#readme) of their JavaScript style guide and have published ESLint configurations to enforce it.
### Custom rules configurations
Below are some rules specific to this configuration.
#### Best practices
Some rules considered as best practices.
| Rule | Configuration |
|------------------------------------------------------------------------------|--------------------------------|
| [`curly`](https://eslint.org/docs/rules/curly) | `['error', 'all']` |
| [`dot-notation`](https://eslint.org/docs/rules/dot-notation) | `'warn'` |
| [`eqeqeq`](https://eslint.org/docs/rules/eqeqeq) | `['warn', 'always']` |
| [`no-alert`](https://eslint.org/docs/rules/no-alert) | `'error'` |
| [`no-empty-function`](https://eslint.org/docs/rules/no-empty-function) | `'error'` |
| [`no-eval`](https://eslint.org/docs/rules/no-eval) | `'error'` |
| [`no-implicit-coercion`](https://eslint.org/docs/rules/no-implicit-coercion) | `['error', { allow: ['!!'] }]` |
| [`no-implicit-globals`](https://eslint.org/docs/rules/no-implicit-globals) | `'error'` |
| [`no-multi-spaces`](https://eslint.org/docs/rules/no-multi-spaces) | `'warn'` |
| [`no-param-reassign`](https://eslint.org/docs/rules/no-param-reassign) | `['warn', { props: false }]` |
| [`no-useless-concat`](https://eslint.org/docs/rules/no-useless-concat) | `'warn'` |
| [`no-useless-return`](https://eslint.org/docs/rules/no-useless-return) | `'warn'` |
| [`strict`](https://eslint.org/docs/rules/strict) | `['error', 'function']` |
| [`vars-on-top`](https://eslint.org/docs/rules/vars-on-top) | `'error'` |
| [`wrap-iife`](https://eslint.org/docs/rules/wrap-iife) | `['error', 'any']` |
| [`yoda`](https://eslint.org/docs/rules/yoda) | `['error', 'never']` |
#### Possible errors
These rules help developpers avoir some possible errors.
| Rule | Configuration |
|------------------------------------------------------------|-----------------------------------------------------------|
| [`no-console`](https://eslint.org/docs/rules/no-console) | `process.env.NODE_ENV !== 'production' ? 'off' : 'error'` |
| [`no-debugger`](https://eslint.org/docs/rules/no-debugger) | `process.env.NODE_ENV !== 'production' ? 'off' : 'error'` |
#### Stylistic issues
<table>
<thead>
<tr>
<th>Rule</th>
<th>Configuration</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="https://eslint.org/docs/rules/array-bracket-spacing"><code>array-bracket-spacing</code></a></td>
<td>
<pre>[
'warn',
'always',
{
arraysInArrays: false,
objectsInArrays: false
},
]</pre>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/camelcase"><code>camelcase</code></a></td>
<td>
<code>['warn', { properties: 'always' }]</code>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/comma-dangle"><code>comma-dangle</code></a></td>
<td>
<code>['warn', 'always-multiline']</code>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/comma-spacing"><code>comma-spacing</code></a></td>
<td>
<code>['warn', { before: false, after: true }]</code>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/indent"><code>indent</code></a></td>
<td>
<code>['warn', 2]</code>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/max-len"><code>max-len</code></a></td>
<td>
<pre>[
'warn',
{
code: 80,
ignoreUrls: true,
ignoreRegExpLiterals: true
},
]</pre>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/no-multi-assign"><code>no-multi-assign</code></a></td>
<td>
<code>'warn'</code>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/no-trailing-spaces"><code>no-trailing-spaces</code></a></td>
<td>
<code>'warn'</code>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/no-unneeded-ternary"><code>no-unneeded-ternary</code></a></td>
<td>
<code>'warn'</code>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/quotes"><code>quotes</code></a></td>
<td>
<code>['warn', 'single']</code>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/require-jsdoc"><code>require-jsdoc</code></a></td>
<td>
<pre>[
'warn',
{
require: {
FunctionDeclaration: true,
MethodDefinition: true,
ClassDeclaration: true,
ArrowFunctionExpression: false,
FunctionExpression: false,
},
},
]</pre>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/semi"><code>semi</code></a></td>
<td>
<code>['warn', 'always']</code>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/semi-style"><code>semi-style</code></a></td>
<td>
<code>['warn', 'last']</code>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/space-before-blocks"><code>space-before-blocks</code></a></td>
<td>
<code>'warn'</code>
</td>
</tr>
</tbody>
</table>
#### ES6
| Rule | Configuration |
|----------------------------------------------------------------------------------|-------------------------------------------|
| [`arrow-spacing`](https://eslint.org/docs/rules/arrow-spacing) | `['warn', { before: true, after: true }]` |
| [`no-var`](https://eslint.org/docs/rules/no-var) | `'error'` |
| [`object-shorthand`](https://eslint.org/docs/rules/object-shorthand) | `'error'` |
| [`prefer-const`](https://eslint.org/docs/rules/prefer-const) | `'error'` |
| [`prefer-template`](https://eslint.org/docs/rules/prefer-template) | `'error'` |
| [`rest-spread-spacing`](https://eslint.org/docs/rules/rest-spread-spacing) | `['warn', 'never']` |
| [`template-curly-spacing`](https://eslint.org/docs/rules/template-curly-spacing) | `['warn', 'never']`
### Overrides
Overrides are used to define specific configuration for sets of limited file globs.
### Build files
Used for: `webpack.config.js, gulpfile.js, nuxt.config.js, webpack.mix.js`
| Rule | Configuration |
|-|-|
| [`global-require`](https://eslint.org/docs/rules/global-require) | `off` |
### Prettier
Used for: `*.js`
The `plugin:prettier/recommended` plugin turns off all ESLint stylistic rules that might conflict with [Prettier](https://github.com/prettier/prettier). You can find out more on the [project's repository](https://github.com/prettier/eslint-config-prettier#readme). |
### Vue
Used for: `*.vue`
For all `*.vue` files, we use the [official ESLint plugin](https://eslint.vuejs.org/) created by Vue.js. The following rules are also specified:
<table>
<thead>
<tr>
<th>Rule</th>
<th>Configuration</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="https://eslint.vuejs.org/rules/html-closing-bracket-newline.html">code>vue/html-closing-bracket-newline</code></a></td>
<td>
<pre>[
'error',
{
singleline: 'never',
multiline: 'never',
},
]</pre>
</td>
</tr>
<tr>
<td><a href="https://eslint.org/docs/rules/indent"><code>indent</code></a></td>
<td><code>'off'</code></td>
</tr>
<tr>
<td><a href="https://eslint.vuejs.org/rules/script-indent.html"><code>vue/script-indent</code></a></td>
<td>
<pre>[
'error',
2,
{
baseIndent: 1,
switchCase: 1,
},
]</pre>
</td>
</tr>
</tbody>
</table>
<file_sep>/src/rules/es6.js
module.exports = {
rules: {
'arrow-spacing': 'off',
'no-var': 'error',
'object-shorthand': 'error',
'prefer-const': 'error',
'prefer-template': 'error',
'rest-spread-spacing': ['warn', 'never'],
'template-curly-spacing': ['warn', 'never'],
},
};
<file_sep>/src/index.js
require('@rushstack/eslint-patch/modern-module-resolution');
module.exports = {
root: true,
extends: [
'eslint:recommended',
'eslint-config-airbnb-base',
require.resolve('./rules/best-practices.js'),
require.resolve('./rules/possible-errors.js'),
require.resolve('./rules/stylistic-issues.js'),
require.resolve('./rules/es6.js'),
require.resolve('./rules/jsdoc.js'),
],
parser: '@babel/eslint-parser',
parserOptions: {
requireConfigFile: false,
},
env: {
browser: true,
es6: true,
},
overrides: [
require('./overrides/build-files.js'),
require('./overrides/jest.js'),
require('./overrides/prettier.js'),
require('./overrides/vue.js'),
require('./overrides/typescript.js'),
{
files: ['*.js'],
extends: [require.resolve('./rules/import.js')],
},
],
};
<file_sep>/src/rules/best-practices.js
module.exports = {
plugins: ['eslint-plugin-unicorn'],
rules: {
curly: ['error', 'all'],
'dot-notation': 'warn',
eqeqeq: ['warn', 'always'],
'no-alert': 'error',
'no-empty-function': 'error',
'no-eval': 'error',
'no-implicit-coercion': ['error', { allow: ['!!'] }],
'no-implicit-globals': 'error',
'no-multi-spaces': 'warn',
'no-param-reassign': ['warn', { props: false }],
'no-useless-concat': 'warn',
'no-useless-return': 'warn',
strict: ['error', 'function'],
'vars-on-top': 'error',
'wrap-iife': ['error', 'any'],
yoda: ['error', 'never'],
'class-methods-use-this': 'off',
'unicorn/no-array-method-this-argument': 'error',
'unicorn/no-array-push-push': 'error',
'unicorn/no-console-spaces': 'error',
'unicorn/no-document-cookie': 'error',
'unicorn/no-for-loop': 'error',
'unicorn/no-instanceof-array': 'error',
'unicorn/no-invalid-remove-event-listener': 'error',
'unicorn/no-lonely-if': 'error',
'unicorn/no-object-as-default-parameter': 'error',
'unicorn/no-unreadable-array-destructuring': 'error',
'unicorn/no-useless-length-check': 'error',
'unicorn/no-useless-spread': 'error',
'unicorn/no-useless-undefined': 'error',
'unicorn/prefer-add-event-listener': 'error',
'unicorn/prefer-array-find': 'error',
'unicorn/prefer-array-flat': 'error',
'unicorn/prefer-array-flat-map': 'error',
'unicorn/prefer-array-index-of': 'error',
'unicorn/prefer-array-some': 'error',
'unicorn/prefer-at': 'error',
'unicorn/prefer-date-now': 'error',
'unicorn/prefer-default-parameters': 'error',
'unicorn/prefer-dom-node-append': 'error',
'unicorn/prefer-dom-node-dataset': 'error',
'unicorn/prefer-dom-node-remove': 'error',
'unicorn/prefer-dom-node-text-content': 'error',
'unicorn/prefer-includes': 'error',
'unicorn/prefer-keyboard-event-key': 'error',
'unicorn/prefer-modern-dom-apis': 'error',
'unicorn/prefer-negative-index': 'error',
'unicorn/prefer-number-properties': 'error',
'unicorn/prefer-object-from-entries': 'error',
'unicorn/prefer-object-has-own': 'error',
'unicorn/prefer-optional-catch-binding': 'error',
'unicorn/prefer-query-selector': 'error',
'unicorn/prefer-regexp-test': 'error',
'unicorn/prefer-set-has': 'error',
'unicorn/prefer-string-replace-all': 'error',
'unicorn/prefer-string-slice': 'error',
'unicorn/prefer-string-starts-ends-with': 'error',
'unicorn/prefer-string-trim-start-end': 'error',
'unicorn/prevent-abbreviations': 'off',
'unicorn/throw-new-error': 'error',
},
};
<file_sep>/.eslintrc.js
module.exports = {
...require('./src/index.js'),
env: {
node: true,
browser: false,
},
rules: {
'global-require': 'off',
},
};
<file_sep>/src/overrides/prettier.js
module.exports = {
files: ['*.js', '*.mjs', '*.cjs', '*.ts', '*.mts', '*.cts', '*.vue', '*.md'],
extends: ['plugin:prettier/recommended'],
};
|
627c0cd14fcce27c364f8d0732c9dd8b4bd188ab
|
[
"JavaScript",
"Markdown"
] | 14
|
JavaScript
|
studiometa/eslint-config
|
8ec1037f08bbf3af2dafaa43756cbb2e40f0a0bc
|
b633f2f0ca759a75ff391f9ea6d6b72521525d31
|
refs/heads/master
|
<repo_name>austitech/Tokenizer<file_sep>/tokenizer.py
from token import Token
class StringTokenizer:
def __init__(self, text='', tokentype=None, keyword=None):
self.text = text
self.tokentype = tokentype
self.keyword = keyword
self.pos = 0 # act as a cursor within self.text
self.current_char = self.text[self.pos]
def advance(self):
"""
increment self.pos by 1.
if self.pos is greater than length of self.text
set self.current_char to character on index
self.pos in self.text
else
set self.current_char to None
"""
self.pos += 1
if self.pos < len(self.text):
self.current_char = self.text[self.pos]
else:
self.current_char = None
def skip_whitespace(self):
"""Skips spaces in the text that are not quoted"""
while self.current_char is not None and self.current_char.isspace():
self.advance()
def get_integer(self):
"""returns an integer when called"""
string = ''
while self.current_char is not None and self.current_char.isdigit():
string += self.current_char
self.advance()
return int(string)
def number(self):
"""recognizes and returns an integer or float token"""
integer = self.get_integer()
if self.current_char == '.':
self.advance()
floating = float(str(integer) + str(self.get_integer()))
return Token(self.tokentype['FLOAT'], floating)
return Token(self.tokentype['INT'], integer)
def identifier(self):
"""recognizes and returns an identifier token"""
_id = ''
while self.current_char is not None and self.current_char.isalpha():
# inner loop to get alphanumeric characters
while self.current_char is not None and\
self.current_char.isalnum():
_id += self.current_char
self.advance()
return Token(self.tokentype['ID'], _id)
def string(self):
"""recognizes and returns a string token"""
_string = ''
while self.current_char != '"':
_string += self.current_char
self.advance()
# return CHARACTER token if length of string is less than 2
if len(_string) == 1:
return Token(self.tokentype['CHAR'], _string)
return Token(self.tokentype['STRING'], _string)
def generic_token(self, character):
"""returns single character tokens"""
return Token(self.tokentype[character], character)
def create_token_generator(self):
"""
move through the text and generates a list of tokens
return token_list:list
"""
while self.current_char is not None:
# handle whitespaces
if self.current_char.isspace():
self.skip_whitespace()
continue
# handle integer and float numbers
if self.current_char.isdigit():
yield self.number()
continue
# handle identifiers e.g variable names
if self.current_char.isalpha():
yield self.identifier()
continue
# handle strings e.g "Hello, World"
if self.current_char == '"':
self.advance() # skip opening quote
yield self.string()
self.advance() # skip closing quote
continue
# handle single characters e.g symbols
if self.current_char in self.tokentype.keys():
char = self.current_char
self.advance()
yield self.generic_token(char)
continue
# add token to indicate end of file (EOF)
yield Token(self.tokentype['EOF'], None)
<file_sep>/token.py
tokentype = {
'INT': 'INT',
'FLOAT': 'FLOAT',
'STRING': 'STRING',
'CHAR': 'CHAR',
'+': 'PLUS',
'-': 'MINUS',
'*': 'MUL',
'/': 'DIV',
'=': 'ASSIGN',
'%': 'MODULO',
':': 'COLON',
';': 'SEMICOLON',
'<': 'LT',
'>': 'GT',
'[': 'O_BRACKET',
']': 'C_BRACKET',
'(': 'O_PAREN',
')': 'C_PAREN',
'{': 'O_BRACE',
'}': 'C_BRACE',
'&': 'AND',
'|': 'OR',
'!': 'NOT',
'^': 'EXPO',
'ID': 'ID',
'EOF': 'EOF'
}
class Token:
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
return f'<{self.type}: {self.value}>'
__repr__ = __str__
<file_sep>/README.md
# Tokenizer
This repository contains 3 modules:
+ tokenizer
+ token
+ example
## tokenizer module
class StringTokenizer
params:
- text: String to break into tokens
- tokentypes: Dictionary of token names
- keyword: Dictionary of reserved names(mostly for programming languages)
the most important method is create_token_generator; builds and returns
a generator object which yields the tokens when needed.
## token module
class Token
params:
- type: Name of token
- value: token value
represents a token object.
## example module
serves as a pointer for however needs help
# Usage
Before you can successfully use StringTokenizer, you must create a dictionary
of token types and values example:
```
tokentype = {
"INT": "INT",
"FLOAT": "FLOAT",
"<": "GT"
}
```
or you can import the default in the token module if it matches your use case.
# Complete Example
### make imports
```
from tokenizer import StringTokenizer
from token import tokentype
```
### create instance of StringTokenizer class and dummy text
```
text = """
names = "<NAME>"
nick = "Austitech"
age = 25
occupation = "Student"
"""
lexer = StringTokenizer(text=text, tokentype=tokentype)
```
### get generator object to yield tokens
```
token_generator = lexer.create_token_generator()
```
### conclusion
Use generator object to yield tokens where needed examples:
```
# get single token
token = next(token_generator)
# using a loop
for token in token_generator:
print(token)
```
# Contributions
Contribution and suggestion of ways to improve is welcome
<file_sep>/example.py
from tokenizer import StringTokenizer
from token import tokentype
text = open('test.ex', 'r').read()
t = StringTokenizer(text=text, tokentype=tokentype)
token_generator = t.create_token_generator()
print(token_generator)
|
d39e586e5056e4e8cbe1e9df5c79c795e646ab67
|
[
"Markdown",
"Python"
] | 4
|
Python
|
austitech/Tokenizer
|
005bd6772ef3298b222c05e3357bf22961978a57
|
f7e770ffeb5aaabffc2de246a04e1c354dfce240
|
refs/heads/master
|
<repo_name>MajaMarkovic1/climate-changes-maps<file_sep>/services.js
class Service{
createServicesList(services, serviceList, selectLabel){
serviceList.innerHTML = '';
services.forEach(element => {
let option = document.createElement("option");
option.textContent = element.name.substring(20);
serviceList.appendChild(option);
});
}
createLayersList(layers, layerslist){
layerslist.forEach(element => {
let div = document.createElement("div");
let checkbox = document.createElement("input");
let label = document.createElement("label");
checkbox.type = "checkbox";
checkbox.value = element.id;
checkbox.checked = element.visible;
label.textContent = element.title;
layers.appendChild(div);
div.appendChild(checkbox);
div.appendChild(label);
this.showLayer(checkbox, layer);
});
}
showLayer(checkbox){
checkbox.addEventListener("click", function(e){
let clickedLayer = layer.findSublayerById(Number(e.target.value));
clickedLayer.visible = e.target.checked;
})
}
}
|
895f8f7e08bd742a0fe4d489fef4dd45ba7a22a3
|
[
"JavaScript"
] | 1
|
JavaScript
|
MajaMarkovic1/climate-changes-maps
|
bcfc7aaefc0a0c4d38f2068acdf5e4ed7ecd401b
|
e50bbfb24fcf91438452ce13138d84d432a70779
|
refs/heads/master
|
<file_sep>#!c:/Python36/python.exe
import os
import argparse
parser = argparse.ArgumentParser(description='[ Unprefix Version 0.1 ] ')
parser.add_argument(
"--path", help=r"python --path C:\Users\TrustedSec\Downloads", required=True)
args = parser.parse_args()
files = os.listdir(args.path)
banner = """
███ █▄ ███▄▄▄▄ ▄███████▄ ▄████████ ▄████████ ▄████████ ▄█ ▀████ ▐████▀
███ ███ ███▀▀▀██▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███▌ ████▀
███ ███ ███ ███ ███ ███ ███ ███ ███ █▀ ███ █▀ ███▌ ███ ▐███
███ ███ ███ ███ ███ ███ ▄███▄▄▄▄██▀ ▄███▄▄▄ ▄███▄▄▄ ███▌ ▀███▄███▀
███ ███ ███ ███ ▀█████████▀ ▀▀███▀▀▀▀▀ ▀▀███▀▀▀ ▀▀███▀▀▀ ███▌ ████▀██▄
███ ███ ███ ███ ███ ▀███████████ ███ █▄ ███ ███ ▐███ ▀███
███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▄███ ███▄
████████▀ ▀█ █▀ ▄████▀ ███ ███ ██████████ ███ █▀ ████ ███▄
███ ███
[ Developed By: @0xSecGuy ]
"""
print(banner)
try:
for f in files:
if not f.startswith('WWW.DOWNVIDS.NET-'):
continue
else:
os.rename(os.path.join(args.path, f),
os.path.join(args.path, f[17:]))
print('Video has been renamed: ' + (f[17:]))
except Exception as e:
print(str(e))
print('\n[+] Mission Completed')
print('[+] Have a nice day!')
<file_sep>## Unprefix
Downvids allows you to download youtube's video, playlist or the whole channel which is awesome.
My issue is that any video downloaded by this website, it is automatically given a prefix name of the website.
* e.g. [WWW.DOWNVIDS.NET-What makes you special.mp4]
## Usage:
python unprefix.py --path C:\Users\TrustedSec\Downloads
## Screenshot

|
b3a1a7051f01801bde17000356da3b113cc11bc9
|
[
"Markdown",
"Python"
] | 2
|
Python
|
anthrax3/Unprefix
|
d8b0277b58505106264efc3f2ffcc9caccbff1da
|
9804b48c04f964cb127646a5a451c23497df3013
|
refs/heads/master
|
<file_sep>import { getFilters } from './filters'
import { getTodos, toggleTodo, removeTodo, saveTodos } from './todos'
const renderTodos = () => {
const newTodosEl = document.querySelector('#newTodos')
// filtering todo list based on typed search text
const todos = getTodos()
const { searchText, hideCompleted } = getFilters()
let filteredTods = todos.filter((todo) => {
const searchTextMatch = todo.text.toLowerCase().includes(searchText.toLowerCase())
// Update hideCompleted an rerender list on checkbox change
const hideCompletedTextMatch = !hideCompleted || !todo.taskCompleted
return searchTextMatch && hideCompletedTextMatch
}
)
//refrehing new html page
newTodosEl.innerHTML = ''
// filtering incomplete Tods
const incompleteTods = filteredTods.filter((todo) => !todo.taskCompleted)
newTodosEl.appendChild(generateSummaryDOM(incompleteTods))
// Add a p for each filtered Tods todo above (use text property)
if (filteredTods.length > 0) {
filteredTods.forEach((todo) => {
newTodosEl.appendChild(generateTodoDOM(todo))
})
}
else {
const emptyMessageEl = document.createElement('p')
emptyMessageEl.classList.add('empty-message')
emptyMessageEl.textContent = 'No to-dos to Show'
newTodosEl.appendChild(emptyMessageEl)
}
}
const generateTodoDOM = (todo) => {
const todoEl = document.createElement('label')
const containerEl = document.createElement('div')
const chekBox = document.createElement('input')
const summary = document.createElement('span')
const button = document.createElement('button')
//setup the checkbox attribute
chekBox.setAttribute('type', 'checkbox')
chekBox.checked = todo.taskCompleted
chekBox.addEventListener('click', (e) => {
toggleTodo(todo.id)
renderTodos()
})
containerEl.appendChild(chekBox)
//setup the todo title text
summary.textContent = todo.text
containerEl.appendChild(summary)
//setup container
todoEl.classList.add('list-item')
containerEl.classList.add('list-item__container')
todoEl.appendChild(containerEl)
//setup remove todo button
button.textContent = 'X'
button.classList.add('button', 'button--text')
todoEl.appendChild(button)
button.addEventListener('click', () => {
removeTodo(todo.id)
renderTodos()
})
return todoEl
}
const generateSummaryDOM = (incompletedTodos) => {
const plural = incompletedTodos.length === 1 ? '' : 's'
const summary = document.createElement('h2')
summary.classList.add('list-title')
summary.textContent = `You have ${incompletedTodos.length} todo${plural} left`
return summary
}
export { renderTodos, generateTodoDOM, generateSummaryDOM }
|
8b518a686a2c14873bcd825b7b8d28df605762a6
|
[
"JavaScript"
] | 1
|
JavaScript
|
MallikarjunKPatil/Projects
|
7b024f0c1be358afedbf0e17be7d2876d3189115
|
28d453eafe7e327f2c0cc5256a5ce353cf2bd249
|
refs/heads/master
|
<repo_name>dorber/ortic<file_sep>/psr/advanced/views/counter.php
<html>
<head>
<title>Advanced Application</title>
</head>
<body>
<h1>Hello <?php echo $counter ?> <?php echo $counter > 1 ? 'times' : 'time' ?>!</h1>
<hr>
<?php include __DIR__ . '/_footer.php'; ?>
</body>
</html><file_sep>/psr/advanced/app/App.php
<?php
namespace App;
use Anonymous\SimpleDi\InvokerInterface;
use function Http\Response\send;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Http\Request;
class App implements RequestHandlerInterface
{
/** @var ContainerInterface|InvokerInterface */
protected $container;
/**
* App constructor.
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* @param ServerRequestInterface $request
* @return ResponseInterface
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->container->call(['dispatcher', 'dispatch'], [$request]);
}
/**
* Runs the dispatcher with the server request
*/
public function run()
{
send($this->handle(Request::createFromGlobals($_SERVER)));
}
}<file_sep>/psr/README.md
# Ortic
[Ortic](../README.md) > PSR и будущее приложений на PHP
### Рекомендации разработчикам
Если вы не знакомы с абривиатурой PSR, рекомендую ознакомиться с [рекомендациями](https://www.php-fig.org/psr/). На
текущий момент приняты следующие стандарты:
* [PSR-1](https://www.php-fig.org/psr/psr-1): Basic Coding Standard
* [PSR-2](https://www.php-fig.org/psr/psr-2): Coding Style Guide
* [PSR-3](https://www.php-fig.org/psr/psr-3): Logger Interface
* [PSR-4](https://www.php-fig.org/psr/psr-4): Autoloading Standard
* [PSR-6](https://www.php-fig.org/psr/psr-6): Caching Interface
* [PSR-7](https://www.php-fig.org/psr/psr-7): HTTP Message Interface
* [PSR-11](https://www.php-fig.org/psr/psr-11): Container Interface
* [PSR-13](https://www.php-fig.org/psr/psr-13): Hypermedia Links
* [PSR-15](https://www.php-fig.org/psr/psr-15): HTTP Handlers
* [PSR-16](https://www.php-fig.org/psr/psr-16): Simple Cache
Сегодня нам особенно интересны два из них PSR-7 и PSR-15, на основе которых постороено дальнейшее повествование.
### Полезные ссылки
* Ссылка на PSR уже была выше, – [обязательно к прочтению](https://www.php-fig.org/psr/), если еще не читали.
* Реализации DI:
* [PHP-DI](http://php-di.org),
* [Simple DI](https://github.com/anonymous-php/simple-di).
* [Сборник ссылок](https://github.com/middlewares/awesome-psr15-middlewares) по тематике PSR-7/PSR-15.
* [Набор мидлваров](https://github.com/middlewares/psr15-middlewares) на все случаи жизни.
* [Сессии](https://github.com/psr7-sessions/storageless) без хранения состояния на стороне сервера.
* Менеджер процессов [PHP-PM](https://github.com/php-pm/php-pm).
### Примеры приложений с использованием PSR-7 и PSR-15
* [Basic application](basic/README.md)
* [Advanced application](advanced/README.md)
<file_sep>/psr/advanced/app/Components/Route/RouteHandler.php
<?php
namespace App\Components\Route;
use Anonymous\SimpleDi\FactoryInterface;
use Anonymous\SimpleDi\InvokerInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class RouteHandler
* @package App\Components\Route
*/
class RouteHandler implements RequestHandlerInterface
{
/** @var ContainerInterface|InvokerInterface|FactoryInterface */
protected $container;
/** @var callable */
protected $handler;
/** @var array */
protected $arguments;
/** @var array */
protected $middlewares;
/**
* RouteHandler constructor.
* @param ContainerInterface $container
* @param $handler
* @param array $arguments
* @param array $middlerwares
*/
public function __construct(ContainerInterface $container, $handler, array $arguments = [], array $middlerwares = [])
{
$this->container = $container;
$this->handler = $handler;
$this->arguments = $arguments;
$this->middlewares = $middlerwares;
}
/**
* Handles request and passes it to routes handler
* @param ServerRequestInterface $request
* @return ResponseInterface
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
// Default arguments
$arguments = [
'request' => $request,
'response' => $this->container->instantiate(ResponseInterface::class),
];
// Routes arguments
foreach ($this->arguments as $argument) {
$arguments[$argument] = $request->getAttribute($argument);
}
// Collect echoes
ob_start();
$response = $this->container->call($this->handler, $arguments);
$output = ob_get_clean();
if (!$response instanceof ResponseInterface) {
$response = $this->container->instantiate(ResponseInterface::class)->write($response);
}
// Write echoes to the end of the response
if (!empty($output) && $response->getBody()->isWritable()) {
$response->getBody()->write($output);
}
return $response;
}
/**
* @return array
*/
public function getMiddlewares()
{
return $this->middlewares;
}
}<file_sep>/psr/basic/definitions/di.php
<?php
use \Psr\Container\ContainerInterface;
return [
\FastRoute\Dispatcher::class => function (ContainerInterface $c) {
return FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) use ($c) {
require __DIR__ . '/routes.php';
});
},
];<file_sep>/README.md
# Ortic
* [PSR и будущее приложений на PHP](psr/README.md)<file_sep>/psr/advanced/app/PmInvoker.php
<?php
namespace App;
use PHPPM\Bootstraps\ApplicationEnvironmentAwareInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* Class PmMiddleware
* @package App
*/
class PmInvoker implements ApplicationEnvironmentAwareInterface
{
/** @var App */
protected $application;
/**
* @param $appenv
* @param $debug
*/
public function initialize($appenv, $debug)
{
$this->application = require __DIR__ . '/bootstrap.php';
}
/**
* @param ServerRequestInterface $request
* @return \Psr\Http\Message\ResponseInterface
* @throws \Exception
*/
public function __invoke(ServerRequestInterface $request)
{
return $this->application->handle($request);
}
}<file_sep>/psr/basic/README.md
# Ortic
[Ortic](../../README.md) > [PSR и будущее приложений на PHP](../README.md) > Basic application
Перед вами полноценное современное приложение на 30 строк кода. Конечно, это число не учитывает код подключаемых
библиотек, но и они не столь велики.
Здесь и контейнер зависимостей, и настоящий роутер, и PSR-7 запрос/ответ. Вы можете возразить, что не хватает
логирования, но и оно добавляется несколькими строками кода (см. [Advanced application](../advanced/README.md)).
Давайте посмотрим на код приложения и начнем с подключаемых библиотек. Тут все достаточно просто:
* Контейнер зависимостей (можно использовать [PHP-DI](http://php-di.org) или, как в этом примере, Simple DI),
* Функция для вывода ответа сервера,
* Мидлвары (те самые кирпичики, из которых состоит очередь преобразования запроса в ответ),
* Диспетчер,
* Реализация запросов и ответов от [Slim Framework](https://www.slimframework.com) (не то, чтобы обязательно было
использовать именно эту реализацию, но она подкупает удобством использования).
[composer.json](composer.json)
```json
{
"require": {
"anonymous-php/simple-di": "^1.1",
"http-interop/response-sender": "^1.0",
"middlewares/error-handler": "^1.0",
"middlewares/fast-route": "^1.0",
"middlewares/request-handler": "^1.1",
"oscarotero/middleland": "^1.0",
"slim/http": "^0.3.0"
}
}
```
Как было упомянуто выше, цель диспетчера обеспечить вызов цепочки мидлваров и вернуть PSR-7 ответ серверу. Любой из
участников цепочки может вернуть ответ или передать управление дальше.
Видно, что в этом примере мы используем три мидлвара:
* Обработчик ошибок,
* Роутер [FastRoute](https://github.com/nikic/FastRoute),
* Обработчик запроса.
В простейшем случае нет необходимости использовать одновременно роутер и обработчик запроса и можно остановиться на
реализации, которая сразу же подготовит ответ в роутере. Но как мы увидим дальше (см.
[Advanced application](../advanced/README.md)), вариант с двумя шагами позволит добавлить гибкости при обработке
запроса.
[public/index.php](public/index.php)
```php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
$container = new \Anonymous\SimpleDi\Container(
require __DIR__ . '/../definitions/di.php', true);
$dispatcher = new \Middleland\Dispatcher([
\Middlewares\ErrorHandler::class,
\Middlewares\FastRoute::class,
\Middlewares\RequestHandler::class,
], $container);
\Http\Response\send($container->call(
[$dispatcher, 'dispatch'],
[\Slim\Http\Request::createFromGlobals($_SERVER)]
));
```
Файл зависимостей для нашего приложения описывает только фабрику для получения диспетчера роутера, которому мы передаем
наши роуты.
[definitions/di.php](definitions/di.php)
```php
<?php
use \Psr\Container\ContainerInterface;
return [
\FastRoute\Dispatcher::class => function (ContainerInterface $c) {
return FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) use ($c) {
require __DIR__ . '/routes.php';
});
},
];
```
Сами роуты выглядят вполне обычно. В этом примере используется фабрика `response()`, возвращающая экземпляр ответа в
обход контейнера зависимостей, но правильным решением в настоящем приложении было бы использование инъекции.
[definitions/routes.php](definitions/routes.php)
```php
<?php
namespace Routes;
use \Psr\Http\Message\ServerRequestInterface;
// Синтаксический сахар, скорее, пример плохого кода в данном случае
function response() { return new \Slim\Http\Response(); }
/**
* @var \FastRoute\RouteCollector $r
* @var \Psr\Container\ContainerInterface|\Anonymous\SimpleDi\FactoryInterface $c
*/
$r->get('/', function () use ($c) {
// Лучше использовать зависимость от интерфейса, не хотелось излишне усложнять текущий пример
return $c->instantiate(\Slim\Http\Response::class)->write('Hello, World!');
});
$r->get('/{name:[a-zA-Z0-9_-]+}', function (ServerRequestInterface $request) {
return response()->write("Hello, {$request->getAttribute('name')}!");
});
```
Здесь пробрасывается переменная `$c`, содержащая указатель на контейнер. Таким образом мы имеем возможность получить из
контейнера необходимые зависимости без автоматических связывания и инъекции.
Реализация полноценного Dependency Injection разобрана в [Advanced application](../advanced/README.md).<file_sep>/psr/advanced/definitions/middleware.php
<?php
return [
\Middlewares\ErrorHandler::class,
\Middlewares\FastRoute::class,
\App\Middlewares\RouteMiddlewares::class,
\Middlewares\RequestHandler::class,
];<file_sep>/psr/advanced/app/Components/Route/RouteCollector.php
<?php
namespace App\Components\Route;
use FastRoute\DataGenerator;
use FastRoute\RouteParser;
use Psr\Container\ContainerInterface;
/**
* Class RouteCollector
* @package App\Components\Route
*/
class RouteCollector extends \FastRoute\RouteCollector
{
protected $currentGroupMiddlewares = [];
protected $container;
/**
* @inheritdoc
*/
public function __construct(ContainerInterface $container, RouteParser $routeParser, DataGenerator $dataGenerator)
{
$this->container = $container;
parent::__construct($routeParser, $dataGenerator);
}
/**
* Alias for addRoute method
* @param $httpMethod
* @param $route
* @param $handler
* @param array $middlewares List of middlewares
*/
public function map($httpMethod, $route, $handler, array $middlewares = [])
{
$this->addRoute($httpMethod, $route, $handler, $middlewares);
}
/**
* @inheritdoc
* @param array $middlewares List of middlewares
*/
public function addRoute($httpMethod, $route, $handler, array $middlewares = [])
{
// Group prefix
$route = $this->currentGroupPrefix . $route;
// Inherit group middlewares
$routeMiddlewares = array_merge($this->currentGroupMiddlewares, $middlewares);
$routeDatas = $this->routeParser->parse($route);
// Collect arguments names to inject them in the future
$arguments = [];
foreach ($routeDatas as $routeData) {
foreach ($routeData as $parts) {
if (!is_array($parts)) {
continue;
}
$argument = reset($parts);
$arguments[$argument] = $argument;
}
}
// Wrap route handler
$routeHandler = new RouteHandler($this->container, $handler, $arguments, $routeMiddlewares);
// Add routes for all methods
foreach ((array) $httpMethod as $method) {
foreach ($routeDatas as $routeData) {
$this->dataGenerator->addRoute($method, $routeData, $routeHandler);
}
}
}
/**
* Alias for addGroup method
* @param $prefix
* @param callable $callback
* @param array $middlewares
*/
public function group($prefix, callable $callback, array $middlewares = [])
{
$this->addGroup($prefix, $callback, $middlewares);
}
/**
* @inheritdoc
* @param array $middlewares List of middlewares
*/
public function addGroup($prefix, callable $callback, array $middlewares = [])
{
$previousMiddlewares = $this->currentGroupMiddlewares;
$this->currentGroupMiddlewares = array_merge($previousMiddlewares, $middlewares);
parent::addGroup($prefix, $callback);
$this->currentGroupMiddlewares = $previousMiddlewares;
}
/**
* @inheritdoc
* @param array $middlewares List of middlewares
*/
public function get($route, $handler, array $middlewares = [])
{
$this->addRoute('GET', $route, $handler, $middlewares);
}
/**
* @inheritdoc
* @param array $middlewares List of middlewares
*/
public function post($route, $handler, array $middlewares = [])
{
$this->addRoute('POST', $route, $handler, $middlewares);
}
/**
* @inheritdoc
* @param array $middlewares List of middlewares
*/
public function put($route, $handler, array $middlewares = [])
{
$this->addRoute('PUT', $route, $handler, $middlewares);
}
/**
* @inheritdoc
* @param array $middlewares List of middlewares
*/
public function delete($route, $handler, array $middlewares = [])
{
$this->addRoute('DELETE', $route, $handler, $middlewares);
}
/**
* @inheritdoc
* @param array $middlewares List of middlewares
*/
public function patch($route, $handler, array $middlewares = [])
{
$this->addRoute('PATCH', $route, $handler, $middlewares);
}
/**
* @inheritdoc
* @param array $middlewares List of middlewares
*/
public function head($route, $handler, array $middlewares = [])
{
$this->addRoute('GET', $route, $handler, $middlewares);
}
}<file_sep>/psr/basic/definitions/routes.php
<?php
namespace Routes;
use \Psr\Http\Message\ServerRequestInterface;
function response() { return new \Slim\Http\Response(); }
/**
* @var \FastRoute\RouteCollector $r
* @var \Psr\Container\ContainerInterface|\Anonymous\SimpleDi\FactoryInterface $c
*/
$r->get('/', function () use ($c) {
return $c->instantiate(\Slim\Http\Response::class)->write('Hello, World!');
});
$r->get('/{name:[a-zA-Z0-9_-]+}', function (ServerRequestInterface $request) {
return response()->write("Hello, {$request->getAttribute('name')}!");
});<file_sep>/psr/advanced/definitions/routes.php
<?php
use App\Controllers\HelloAction;
use App\Controllers\IndexController;
use App\Components\Route\RouteCollector;
use PSR7Sessions\Storageless\Http\SessionMiddleware;
/**
* @var RouteCollector $r
*/
$r->get('/', [IndexController::class, 'index']);
$r->group('/', function (RouteCollector $r) {
$r->get('counter', [IndexController::class, 'counter']);
$r->get('counter/minus', [IndexController::class, 'minus']);
}, [SessionMiddleware::class]);
$r->get('/exception', function () {
throw new Exception('Test exception');
});
$r->get('/{name:[a-zA-Z0-9_-]+}', HelloAction::class);
<file_sep>/psr/advanced/app/Controllers/HelloAction.php
<?php
namespace App\Controllers;
use App\Components\View\ViewInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* Class HelloAction
* @package App\Controllers
*/
class HelloAction
{
/**
* @param ViewInterface $view
* @param ServerRequestInterface $request
* @param $name
* @return mixed
*/
public function __invoke(ViewInterface $view, ServerRequestInterface $request, $name)
{
return $view->render('hello', ['name' => $name, 'request' => $request]);
}
}<file_sep>/psr/advanced/README.md
# Ortic
[Ortic](../../README.md) > [PSR и будущее приложений на PHP](../README.md) > Advanced application
Давайте теперь посмотрим, чего не хватает или что мы можем добавить, чтобы улучшить наше приложение:
* Инъекция зависимостей,
* Мидлвары для роутов,
* Сессия,
* Еще больше скорости.
В первую очередь разберем на части наш `index.php`, реализуем простейший класс приложения [`App`](app/App.php),
инстанцирование которого вынесем в отдельный файл [`bootstrap.php`](app/bootstrap.php):
```php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
$container = new \Anonymous\SimpleDi\Container(require __DIR__ . '/../definitions/di.php', true);
return new \App\App($container);
```
Диспетчер обработки запроса уходит в [файл описания](definitions/di.php) контейнера зависимостей, где получает список
мидлваров приложения из одноименного файла:
```php
<?php
return [
'dispatcher' => function (ContainerInterface $c) {
return new \Middleland\Dispatcher(
require __DIR__ . '/middleware.php',
$c
);
},
// ...
];
```
В итоге [`index.php`](public/index.php) прилично похудел:
```php
<?php
(require __DIR__ . '/../app/bootstrap.php')->run();
```
Текущий способ подключения FastRoute не поддерживает инъекцию зависимостей, давайте это исправим. Есть несколько
вариантов решения проблемы, одним из которых является переопределение метода, который запускает обработчик (`handler`)
роута, – в нашем случае это мидвар `Middlewares\RequestHandler`. Или мы можем переопределить обработчик роута, решив
заодно вторую поставленную перед нами задачу "Мидлвары для роутов".
Переопределим [`RouteCollector`](app/Components/Route/RouteCollector.php), расширив его методы таким образом, чтобы они
принимали еще одним параметром список мидлваров, а при добавлении роута оборачивали его обработчик в нашу обертку:
```php
<?php
// ...
public function addRoute($httpMethod, $route, $handler, array $middlewares = [])
{
// ...
$routeHandler = new RouteHandler($this->container, $handler, $arguments, $routeMiddlewares);
// ...
}
```
[`RouteHandler`](app/Components/Route/RouteCollector.php) имеет информацию о привязанных мидлварах и умеет запустить на
выполнение оригинальный обработчик роута с полноценной инъекцией зависимостей.
Если заглянуть в [файл](definitions/middleware.php) со списком основых мидлваров приложения, можно заметить, здесь
появился еще один мидлвар `RouteMiddlewares`. Его предназначение в том, чтобы получить список мидлваров для роута и
обработать их, вернув ответ или передав управление дальше.
```php
<?php
return [
\Middlewares\ErrorHandler::class,
\Middlewares\FastRoute::class,
\App\Middlewares\RouteMiddlewares::class,
\Middlewares\RequestHandler::class,
];
```
Таким образом можно производить, например, проверки прав доступа до запуска обработчика роута, который тянет за собой
инъекцию сервиса с подключением к базе данных. Или как в нашем примере, инициализировать сессию для определенной группы
роутов.
```php
<?php
use App\Controllers\HelloAction;
use App\Controllers\IndexController;
use App\Components\Route\RouteCollector;
use PSR7Sessions\Storageless\Http\SessionMiddleware;
/**
* @var RouteCollector $r
*/
$r->get('/', [IndexController::class, 'index']);
$r->group('/', function (RouteCollector $r) {
$r->get('counter', [IndexController::class, 'counter']);
$r->get('counter/minus', [IndexController::class, 'minus']);
}, [SessionMiddleware::class]);
$r->get('/exception', function () {
throw new Exception('Test exception');
});
$r->get('/{name:[a-zA-Z0-9_-]+}', HelloAction::class);
```
Раз уж речь зашла о сессиях, стоит упомянуть, в этом приложении используется
[реализация сессиии](https://github.com/psr7-sessions/storageless) без хранения состояния на сервере. Подход, похожий на
JWT. Данные подписываются секретным ключем, а в качестве хранилища используются куки на стороне пользователя. Stateless
архитектура положительно сказывается на возможности горизонтального масштабирования приложения.
Не так давно вышел первый релиз менеджера процессов [PHP-PM](https://github.com/php-pm/php-pm), который позволяет
вашему приложению один раз инициализировать все подключения и произвести ресурсоемкие операции и далее просто
обрабатывать поступающие запросы. О подробностях реализации и преимуществах данного подхода я предлагаю вам прочитать на
странице проекта, а здесь давайте подключим PHP-PM к нашему приложению:
```bash
composer require php-pm/php-pm
```
Все подключение сводится к реализации класса адаптера [`PmInvoker`](app/PmInvoker.php), в котором инициализируется
приложение и реализуется метод для запуска обработчика запросов.
```php
<?php
namespace App;
use PHPPM\Bootstraps\ApplicationEnvironmentAwareInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* Class PmMiddleware
* @package App
*/
class PmInvoker implements ApplicationEnvironmentAwareInterface
{
/** @var App */
protected $application;
/**
* @param $appenv
* @param $debug
*/
public function initialize($appenv, $debug)
{
$this->application = require __DIR__ . '/bootstrap.php';
}
/**
* @param ServerRequestInterface $request
* @return \Psr\Http\Message\ResponseInterface
* @throws \Exception
*/
public function __invoke(ServerRequestInterface $request)
{
return $this->application->handle($request);
}
}
```
Пример сохраненной конфигурации для PHP-PM можно найти в файле [`ppm.json`](ppm.json):
```json
{
"bridge": "InvokableMiddleware",
"host": "0.0.0.0",
"port": 8080,
"workers": 2,
"app-env": "prod",
"debug": 0,
"logging": 0,
"static-directory": "public\/",
"bootstrap": "App\\PmInvoker",
"max-requests": 1000,
"populate-server-var": true,
"socket-path": "storage\/ppm\/run\/",
"pidfile": "storage\/ppm\/ppm.pid"
}
```
Если ваше приложение не хранит состояние на сервере, вы можете запустить сколь угодно много его экземпляров, обеспечив
таким образом простое и эффективное масштабирование без необходимости обеспечения доступа к хранилищу состояний и
поддержания его целостности.
При обсуждении [Basic application](../basic/README.md) я обещал рассказать о логировании. Тут все очень просто:
* Определяем свой `ErrorHandler`, наследующий `Middlewares\ErrorHandlerDefault`,
* Описываем зависимость обработчика ошибок от нашего `ErrorHandler` и реализации логгера
* Разрешаем обработчику перехватывать необработанные исключения
* Логируем ошибки в методе `handle`
```php
<?php
return [
// ...
\Middlewares\ErrorHandler::class => function (ContainerInterface $c) {
$handler = new \Middlewares\ErrorHandler(
new \App\Components\ErrorHandler($c->get(\Psr\Log\LoggerInterface::class))
);
$handler->catchExceptions();
return $handler;
},
// ...
];
```
Свой обработчик ошибок требуется так же в случае, если вы хотите оформить страницы ошибок в дизайне приложения.
А дальше на ваш вкус: сервисы, репозитории, модели, шаблонизаторы.
Таким я вижу будущее приложений на PHP. <file_sep>/psr/basic/public/index.php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
$container = new \Anonymous\SimpleDi\Container(require __DIR__ . '/../definitions/di.php', true);
$dispatcher = new \Middleland\Dispatcher([
\Middlewares\ErrorHandler::class,
\Middlewares\FastRoute::class,
\Middlewares\RequestHandler::class,
], $container);
\Http\Response\send($container->call(
[$dispatcher, 'dispatch'],
[\Slim\Http\Request::createFromGlobals($_SERVER)]
));
<file_sep>/psr/advanced/views/hello.php
<html>
<head>
<title>Advanced Application</title>
</head>
<body>
<h1>Hello, <?php echo $name; ?>!</h1>
<hr>
<?php include __DIR__ . '/_footer.php'; ?>
</body>
</html><file_sep>/psr/advanced/views/_footer.php
<?php echo $this->link('Main', '/', $request->getUri()->getPath()) ?> |
<?php echo $this->link('Dima', '/Dima', $request->getUri()->getPath()) ?> |
<?php echo $this->link('Counter', '/counter', $request->getUri()->getPath()) ?> |
<?php echo $this->link('Counter minus', '/counter/minus', $request->getUri()->getPath()) ?> |
<?php echo $this->link('Exception', '/exception', $request->getUri()->getPath()) ?>
<file_sep>/psr/advanced/app/bootstrap.php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
$container = new \Anonymous\SimpleDi\Container(require __DIR__ . '/../definitions/di.php', true);
return new \App\App($container);<file_sep>/psr/advanced/app/Components/View/ViewInterface.php
<?php
namespace App\Components\View;
interface ViewInterface
{
/**
* Renders template with passed params
* @param $template
* @param array $params
* @return mixed
*/
public function render($template, $params = []);
}<file_sep>/psr/advanced/app/Components/ErrorHandler.php
<?php
namespace App\Components;
use Middlewares\ErrorHandlerDefault;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
/**
* Class ErrorHandler
* @package App\Components
*/
class ErrorHandler extends ErrorHandlerDefault
{
/** @var LoggerInterface */
protected $logger;
/**
* ErrorHandler constructor.
* @param LoggerInterface $logger
*/
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* @param ServerRequestInterface $request
* @return ResponseInterface
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
/** @var \Throwable $error */
$error = $request->getAttribute('error');
if ($error->getPrevious() instanceof \Throwable && $error->getCode() >= 500 && $error->getCode() < 600) {
$this->logger->error($error->getPrevious());
}
return parent::handle($request);
}
}<file_sep>/psr/advanced/app/Components/View/View.php
<?php
namespace App\Components\View;
/**
* Class View
* @package App\Components\View
*/
class View implements ViewInterface
{
protected $viewsDir;
/**
* View constructor.
* @param $viewsDir
*/
public function __construct($viewsDir)
{
$this->viewsDir = $viewsDir;
}
/**
* @inheritdoc
*/
public function render($template, $params = [])
{
$template = preg_match('/\.php$/i', $template) ? $template : $template . '.php';
extract($params);
ob_start();
require $this->viewsDir . '/' . $template;
return ob_get_clean();
}
/**
* Link renderer. Syntax sugar
* @param $text
* @param null $href
* @param null $link
* @return string
*/
protected function link($text, $href = null, $link = null)
{
return $link && $link == $href
? "<span>{$text}</span>"
: "<a href='{$href}'>{$text}</a>";
}
}<file_sep>/psr/advanced/definitions/di.php
<?php
use \Psr\Container\ContainerInterface;
return [
'dispatcher' => function (ContainerInterface $c) {
return new \Middleland\Dispatcher(
require __DIR__ . '/middleware.php',
$c
);
},
\Psr\Http\Message\ResponseInterface::class => \Slim\Http\Response::class,
\FastRoute\RouteParser::class => \FastRoute\RouteParser\Std::class,
\FastRoute\DataGenerator::class => \FastRoute\DataGenerator\GroupCountBased::class,
\FastRoute\Dispatcher::class => function (\Anonymous\SimpleDi\FactoryInterface $c) {
/** @var \App\Components\Route\RouteCollector $r */
$r = $c->make(\App\Components\Route\RouteCollector::class);
require __DIR__ . '/routes.php';
return new \FastRoute\Dispatcher\GroupCountBased($r->getData());
},
\App\Components\View\ViewInterface::class => function () {
return new App\Components\View\View(__DIR__ . '/../views');
},
'session.secretKey' => '<KEY>',
'session.cookieName' => 'sid',
'session.ttl' => 1200,
\PSR7Sessions\Storageless\Http\SessionMiddleware::class => function (ContainerInterface $c) {
$secret = $c->get('session.secretKey');
return new \PSR7Sessions\Storageless\Http\SessionMiddleware(
new \Lcobucci\JWT\Signer\Hmac\Sha384(),
$secret,
$secret,
\Dflydev\FigCookies\SetCookie::create($c->get('session.cookieName'))
->withHttpOnly(true)
->withPath('/'),
new \Lcobucci\JWT\Parser(),
$c->get('session.ttl'),
new \Lcobucci\Clock\SystemClock()
);
},
\Middlewares\ErrorHandler::class => function (ContainerInterface $c) {
$handler = new \Middlewares\ErrorHandler(
new \App\Components\ErrorHandler($c->get(\Psr\Log\LoggerInterface::class))
);
$handler->catchExceptions();
return $handler;
},
'logger.level' => \Monolog\Logger::DEBUG,
'logger.path' => __DIR__ . '/../storage/logs/app.log',
Psr\Log\LoggerInterface::class => function (ContainerInterface $c) {
$handler = new Monolog\Handler\StreamHandler($c->get('logger.path'), $c->get('logger.level'));
$handler->setFormatter(new \Monolog\Formatter\LineFormatter(null, null, true));
$logger = new Monolog\Logger('app');
$logger->pushProcessor(new Monolog\Processor\UidProcessor());
$logger->pushHandler($handler);
return $logger;
},
];<file_sep>/psr/advanced/app/Controllers/IndexController.php
<?php
namespace App\Controllers;
use App\Components\View\ViewInterface;
use Psr\Http\Message\ServerRequestInterface;
use PSR7Sessions\Storageless\Http\SessionMiddleware;
use PSR7Sessions\Storageless\Session\SessionInterface;
/**
* Class IndexController
* @package App\Controllers
*/
class IndexController
{
/** @var ViewInterface */
protected $view;
/**
* IndexController constructor.
* @param ViewInterface $view
*/
public function __construct(ViewInterface $view)
{
$this->view = $view;
}
/**
* @param ServerRequestInterface $request
* @return mixed
*/
public function index(ServerRequestInterface $request)
{
return $this->view->render('hello', ['name' => 'World', 'request' => $request]);
}
/**
* @param ServerRequestInterface $request
* @return mixed
*/
public function counter(ServerRequestInterface $request)
{
/** @var SessionInterface $session */
$session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
$newValue = $session->get('counter') + 1;
$session->set('counter', $newValue);
return $this->view->render('counter', ['counter' => $newValue, 'request' => $request]);
}
/**
* @param ServerRequestInterface $request
* @return mixed
*/
public function minus(ServerRequestInterface $request)
{
/** @var SessionInterface $session */
$session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
$newValue = $session->get('counter') - 1;
$session->set('counter', $newValue);
return $this->view->render('counter', ['counter' => $newValue, 'request' => $request]);
}
}<file_sep>/psr/advanced/app/Middlewares/RouteMiddlewares.php
<?php
namespace App\Middlewares;
use App\Components\Route\RouteHandler;
use Middleland\Dispatcher;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class RouteMiddlewares
* @package App\Middlewares
*/
class RouteMiddlewares implements MiddlewareInterface
{
/** @var ContainerInterface */
protected $container;
/**
* Route constructor.
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* Handles routes middlewares
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$requestHandler = $request->getAttribute('request-handler');
$middlewares = $requestHandler instanceof RouteHandler
? $requestHandler->getMiddlewares()
: [];
return $middlewares
? (new Dispatcher($middlewares, $this->container))->process($request, $handler)
: $handler->handle($request);
}
}
|
1e99fe6fbf3d9bc069ec888490ec4d9edff3a4f6
|
[
"Markdown",
"PHP"
] | 24
|
PHP
|
dorber/ortic
|
3c17d989e044b653d0aa3a0b359825b60a1b506e
|
99280bf5fa846d91ad4adff81aa6fd8f3c39a124
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using JCDecaux_API;
namespace JCDecaux_API {
/// <summary>
/// This class implements the JCDecaux API in order to get all informations about cities and contracts
/// Note : this class also implements the Singleton design pattern.
/// </summary>
public class JCDecaux_Contracts_API {
private String API_KEY;
private String URL = "https://api.jcdecaux.com/vls/v1/contracts?apiKey={{API_KEY}}";
public List<Contract> Contracts { get; set; }
//Unique instance
private static JCDecaux_Contracts_API API_Instance = null;
private static readonly object padlock = new object();
//Constructor. Setting new API key
public JCDecaux_Contracts_API(String API_KEY) {
setAPI(API_KEY);
}
//Get instance of singleton
public static JCDecaux_Contracts_API getInstance {
get {
lock (padlock) {
if (API_Instance == null) {
API_Instance = new JCDecaux_Contracts_API();
}
return API_Instance;
}
}
}
JCDecaux_Contracts_API() {
}
//Setting new URL with API key
public void setAPI(String API) {
API_KEY = API;
URL = URL.Replace("{{API_KEY}}", API);
}
public void feedContracts() {
WebResponse response = WebRequest.Create(URL).GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
Contracts = JsonConvert.DeserializeObject<List<Contract>>(reader.ReadToEnd());
reader.Close();
response.Close();
}
}
}<file_sep>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JCDecaux_API {
public class Position {
[JsonProperty("lat")]
public double Latitude { get; set; }
[JsonProperty("lng")]
public double Longitude { get; set; }
public override string ToString() {
return Longitude + ", " + Latitude;
}
}
public class Station {
[JsonProperty("number")]
public int Number { get; set; }
[JsonProperty("contract_name")]
public string City { get; set; }
[JsonProperty("name")]
public string StationName { get; set; }
[JsonProperty("address")]
public string Address { get; set; }
[JsonProperty("position")]
public Position Position { get; set; }
[JsonProperty("banking")]
public bool Banking { get; set; }
[JsonProperty("bonus")]
public bool Bonus { get; set; }
[JsonProperty("bike_stands")]
public int TotalSpace { get; set; }
[JsonProperty("available_bike_stands")]
public int FreeSpace { get; set; }
[JsonProperty("available_bikes")]
public int AvailableBikes { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("last_update")]
public long LastUpdate { set; get; }
}
}
<file_sep>using JCDecaux_API;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using VLib_Client.VLibSoapService;
using Station = VLib_Client.VLibSoapService.Station;
using Contract = VLib_Client.VLibSoapService.Contract;
namespace VLib_Client {
class RESTClient {
private bool isFullFeed= false;
public RESTClient() {
if (fullFeed()) {
isFullFeed = true;
}
}
private const String __BASE_URL__ = "http://localhost:8733/Design_Time_Addresses/VLibAPI/SOAP/";
public Station[] getAllStationsIn(string city) {
if (isFullFeed) {
WebResponse response = WebRequest.Create(__BASE_URL__ + "getAllStationsIn?city=" + city).GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
return JsonConvert.DeserializeObject<Station[]>(reader.ReadToEnd());
}
throw new Exception("Feed isn't complete.");
}
public Step[] getInstructions(bool isPedestrian, String srcAddress, String destAddres){
if (isFullFeed) {
WebResponse response = WebRequest.Create(__BASE_URL__ + "getInstructions?isPedestrian=" + isPedestrian
+ "&srcAddress=" + srcAddress + "&destAddres=" + destAddres).GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
return JsonConvert.DeserializeObject<Step[]>(reader.ReadToEnd());
}
throw new Exception("Feed isn't complete.");
}
public bool fullFeed() {
return (new StreamReader(WebRequest.Create(__BASE_URL__ + "fullFeed").GetResponse().GetResponseStream()).ReadToEnd().Equals("true"));
}
public Station getStationByName(String name) {
if(isFullFeed) {
WebResponse response = WebRequest.Create(__BASE_URL__ + "getStationByName?name=" + name).GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
return JsonConvert.DeserializeObject<Station>(reader.ReadToEnd());
}
throw new Exception("Feed isn't complete.");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace JCDecaux_API {
/// <summary>
/// This class implements the JCDecaux API in order to get all informations about Velibs of a specific city.
/// Note : this class also implements the Singleton design pattern.
/// </summary>
public class JCDecaux_Stations_API {
private String API_KEY;
private String CITY;
private String URL = "https://api.jcdecaux.com/vls/v1/stations?contract={{VILLE}}&apiKey={{API_KEY}}";
public List<Station> Stations { get; set; }
//Unique instance
private static JCDecaux_Stations_API API_Instance = null;
private static readonly object padlock = new object();
//Constructor. Setting new API key
public JCDecaux_Stations_API(String API_KEY) {
setAPI(API_KEY);
}
//Get instance of singleton
public static JCDecaux_Stations_API getInstance {
get {
lock (padlock) {
if (API_Instance == null) {
API_Instance = new JCDecaux_Stations_API();
}
return API_Instance;
}
}
}
//Default constructor for singleton pattern
JCDecaux_Stations_API() {
}
//Constructor. Setting new API key and city if needed
public JCDecaux_Stations_API(String API_KEY, String city) {
setAPI(API_KEY);
setCity(city);
}
//Setting new URL with city
public void setCity(String city) {
if (city.Equals("")) {
URL = URL.Replace("contract={{VILLE}}&", city);
}
else {
URL = URL.Replace("{{VILLE}}", city);
}
if(CITY != null && !CITY.Equals("")) {
URL = URL.Replace(CITY, city); //In case of new city
}
CITY = city;
}
//Setting new URL with API key
public void setAPI(String API) {
API_KEY = API;
URL = URL.Replace("{{API_KEY}}", API);
}
public static DateTime timestampToDate(double javaTimeStamp) {
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddMilliseconds(javaTimeStamp).ToLocalTime();
return dtDateTime;
}
public void feedStations() {
try {
WebResponse response = WebRequest.Create(URL).GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
Stations = JsonConvert.DeserializeObject<List<Station>>(reader.ReadToEnd());
reader.Close();
response.Close();
} catch (JsonSerializationException e2) {
//do nothing, it's usually an ok-errorr
}catch (Exception e) {
throw e;
}
}
}
}<file_sep>using JCDecaux_API;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web;
namespace VLib_WSSOAP_API {
public class VLibSoapService : IVLibSoapService {
private const string API_KEY = "8542dbcf60bced995bb88e18829cc836c7ec5afe";
private const string GOOGLEMAP_API_KEY = "<KEY>";
/// <param name="doFeed"> If set to true, don't need to call fullFeed() to get all stations and contracts data</param>
public VLibSoapService(bool doFeed) {
if (doFeed) fullFeed();
}
public VLibSoapService() {
}
/// <summary>This method feed all the variable, so you can work with it.</summary>
public bool fullFeed() {
try {
JCDecaux_Contracts_API.getInstance.setAPI(API_KEY);
JCDecaux_Stations_API.getInstance.setAPI(API_KEY);
JCDecaux_Stations_API.getInstance.setCity(""); //no city, we want everything
/*This is the caching system. We get all the data one for all, and store it into our JCDecaux instance.
Then we just need to call the following method in order to get data,
so the real JCDecaux servers won't be "spammed" of requests.*/
JCDecaux_Stations_API.getInstance.feedStations();
JCDecaux_Contracts_API.getInstance.feedContracts();
} catch (Exception error) {
//Returning false if we got any kind of error.
return false;
}
return true;
}
/// <summary>Get all contracts</summary>
List<Contract> IVLibSoapService.getContracts() {
return JCDecaux_Contracts_API.getInstance.Contracts;
}
/// <summary>Get all stations</summary>
List<Station> IVLibSoapService.getStations() {
return JCDecaux_Stations_API.getInstance.Stations;
}
/// <summary>Return a list of Stations located in a given city</summary>
/// <param name="city">The city to get the stations in</param>
List<Station> IVLibSoapService.getAllStationsIn(string city) {
List<Station> stations = new List<Station>();
foreach (Station station in JCDecaux_Stations_API.getInstance.Stations) {
if (station.City.Contains(city)) {
stations.Add(station);
}
}
return stations;
}
private Direction getDirection(bool isPedestrian, string srcAddress, string destAddress) {
String mode = isPedestrian ? "walking" : "bicycling";
String FULL_GMAP_URL = "https://maps.googleapis.com/maps/api/directions/json?origin=" + srcAddress
+ "&destination=" + destAddress + "&mode=" + mode + "&key=" + GOOGLEMAP_API_KEY;
var json = new WebClient().DownloadString(FULL_GMAP_URL);
return JsonConvert.DeserializeObject<Direction>(json);
}
/// <summary>Return a static image of the direction from an address to another</summary>
/// <param name="isPedestrian">Should we use pedestrian algorithm or bike algorithm</param>
/// <param name="srcAddress">Source address</param>
/// <param name="destAddres">Destination address</param>
Bitmap IVLibSoapService.getStaticMapImage(bool isPedestrian,
string srcAddress, string destAddres, bool ignoreException) {
String size = "432x202";
String path = getDirection(isPedestrian, srcAddress, destAddres).routes[0].overview_polyline.points;
String firstMarkerSrc = "color:blue|label:S|" + srcAddress;
String secondMarkerDst = "color:red|label:D|" + destAddres;
String zoom = ""; //could be '&zoom=14'
String FULL_GMAP_URL = "https://maps.googleapis.com/maps/api/staticmap?size="
+ size + "&path=" + path + "&markers=" + firstMarkerSrc + "&markers=" + secondMarkerDst +
"&key=" + GOOGLEMAP_API_KEY;
WebResponse req = WebRequest.Create(FULL_GMAP_URL).GetResponse();
//If the GMAp api returns error
if (req.Headers.Get("X-Staticmap-API-Warning") != "" && !ignoreException) {
throw WrongGMapQueryException(null, FULL_GMAP_URL);
}
return new Bitmap(req.GetResponseStream());
}
/// <summary>Return an exception with HTTP details</summary>
/// <param name="req">WebResponse variable</param>
/// <param name="URL">Complete URL</param>
Exception WrongGMapQueryException(WebClient req, String URL) {
if (req == null) {
return new Exception("Failed. URL : " + URL);
}
return new Exception("Failed. URL : " + URL + ". Headers : " + req.ResponseHeaders);
}
Station IVLibSoapService.getStationByName(string name) {
foreach (Station station in JCDecaux_Stations_API.getInstance.Stations) {
if (station.StationName.Equals(name)) {
return station;
}
}
return null;
}
List<Step> IVLibSoapService.getInstructions(bool isPedestrian, string srcAddress, string destAddres) {
List<Step> instructions = new List<Step>();
foreach (Route route in getDirection(isPedestrian, srcAddress, destAddres).routes) {
foreach (Leg leg in route.legs) {
foreach (Step step in leg.steps) {
instructions.Add((step));
}
}
}
return instructions;
}
}
}
<file_sep>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JCDecaux_API {
public class Contract {
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("commercial_name")]
public string CommercialName { get; set; }
[JsonProperty("cities")]
public List<String> Cities { get; set; }
[JsonProperty("country_code")]
public string CountryCode { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using VLib_Client.VLibSoapService;
namespace VLib_Client {
public partial class Form1 : Form {
VLibSoapServiceClient SOAPClient = new VLibSoapServiceClient();
RESTClient rESTClient = new RESTClient();
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
if (isSOAP.Checked) {
SOAPClient.fullFeed();
} else {
rESTClient.fullFeed();
}
}
private void xylosButton1_Click(object sender, EventArgs e) {
Station[] allStations;
if (isSOAP.Checked) {
allStations = SOAPClient.getAllStationsIn(xylosTextBox2.Text);
} else {
allStations = rESTClient.getAllStationsIn(xylosTextBox2.Text);
}
foreach (Station item in allStations) {
xylosCombobox1.Items.Add(item.StationName);
showItinaryComponents();
}
if (allStations.Length.Equals(0)) {
MessageBox.Show("No stations found in " + xylosTextBox2.Text, "No stations found", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void showItinaryComponents() {
groupBox1.Visible = true;
label2.Visible = true;
label1.Visible = true;
label7.Visible = true;
xylosButton2.Visible = true;
xylosCombobox1.Visible = true;
}
private void xylosCombobox1_SelectedIndexChanged(object sender, EventArgs e) {
lblStationName.Text = xylosCombobox1.SelectedItem.ToString();
if (isSOAP.Checked) {
lblAddress.Text = SOAPClient.getStationByName(xylosCombobox1.SelectedItem.ToString()).Address;
} else {
lblAddress.Text = rESTClient.getStationByName(xylosCombobox1.SelectedItem.ToString()).Address;
}
label1.Visible = true;
}
private void xylosButton2_Click(object sender, EventArgs e) {
if (isSOAP.Checked) {
SOAPClient.fullFeed();
} else {
rESTClient.fullFeed();
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
MessageBox.Show("Mail adress has been copied to clipboard ! ", "Copied", MessageBoxButtons.OK, MessageBoxIcon.Information);
Clipboard.SetData(DataFormats.Text, linkLabel1.Text);
}
private void xylosButton3_Click(object sender, EventArgs e) {
listView1.Visible = false;
pictureBox1.Visible = true;
try {
pictureBox1.Image = SOAPClient.getStaticMapImage(radioPedestrian.Checked ? true : false,
xylosTextBox2.Text, xylosTextBox1.Text, true);
} catch (Exception vertexError) {
if(vertexError.Message.Contains("Failed. URL")) {
MessageBox.Show("The addresses you provided are too far away from each other. Google Static Maps provides a limited" +
" number of vertex to draw lines. We'll still provide you the informations about the route, and the details",
"No vertexes provided", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
private void xylosButton5_Click(object sender, EventArgs e) {
listView1.Items.Clear();
listView1.Visible = true;
pictureBox1.Visible = false;
Step[] instructions;
if (isSOAP.Checked) {
instructions = SOAPClient.getInstructions(radioPedestrian.Checked ? true : false, xylosTextBox2.Text, xylosTextBox1.Text);
} else {
instructions = rESTClient.getInstructions(radioPedestrian.Checked ? true : false, xylosTextBox2.Text, xylosTextBox1.Text);
}
foreach (Step instruction in instructions) {
listView1.Items.Add(new ListViewItem(
new[] {
Regex.Replace(instruction.html_instructions, "<.*?>", String.Empty),
instruction.distance.text,
instruction.duration.text
} ));
}
}
private void isSOAP_CheckedChanged(object sender, EventArgs e) {
if(isSOAP.Checked)
label8.Text = "Current used protocol : REST";
else
label8.Text = "Current used protocol : SOAP";
}
}
}
|
04441e2f6dbf1ebbf6d81af4fd6932f04e369546
|
[
"C#"
] | 7
|
C#
|
kevin-valerio/VLib-WS-SOAP-API
|
e850f7464dba020e5b9e81f38bc85745dad2c26b
|
e5f4aa6e48af37edc86fffd63127b0df0e733e10
|
refs/heads/master
|
<repo_name>crazyfengyu/jewelry<file_sep>/js/common/config.js
function getTodayMonthDays(date) {
var tempDate = new Date("2000-1-1");
tempDate.setFullYear(date.getFullYear());
tempDate.setMonth(date.getMonth() + 1);
tempDate.setDate(0);
return tempDate.getDate();
}
function getTodayMonthOneDaysWeek(date) {
var tempDate = new Date("2000-1-1");
tempDate.setFullYear(date.getFullYear());
tempDate.setMonth(date.getMonth());
return tempDate.getDay() == 0 ? 7 : tempDate.getDay();
}
function setCookie(key, keyValue, days) {
//获取当前时间
var date = new Date();
//设置cookie过期时间
date.setDate(date.getDate() + days);
//将数据写入cookie
document.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(keyValue) + ";expires=" + date + ";path=/";
}
function getCookie(key) {
//获取cookie
var cookieStr = document.cookie;
//判断cookie里面是否有值
if (cookieStr) {
//根据";"拆分cookie字符串
var cookieList = cookieStr.split("; ");
//循环遍历
for (var i = 0; i < cookieList.length; i++) {
//去除每个数组的值
var item = cookieList[i];
var itemList = item.split("=");
if (decodeURIComponent(itemList[0]) == key) {
//获取名称值
var itemKey = decodeURIComponent(itemList[0]);
//获取名称对应的值
var itemValue = decodeURIComponent(itemList[1]);
return itemValue;
}
}
return "";
} else {
return "";
}
}
/**
* 兼容获取向上卷曲的距离
* @returns {number}
*/
function getScrollTop() {
return document.documentElement.scrollTop || document.body.scrollTop;
}
/**
* 兼容获取向左卷曲的距离
* @returns {number}
*/
function getScrollLeft() {
return document.documentElement.scrollLeft || document.body.scrollLeft;
}
/**
* 兼容获取屏幕的可视宽度
* @returns {number}
*/
function getClientWidth() {
return document.documentElement.clientWidth || document.body.clientWidth;
}
/**
* 兼容获取屏幕的可视高度
* @returns {number}
*/
function getClientHeight() {
return document.documentElement.clientHeight || document.body.clientHeight;
}
/**
* 兼容获取页面的宽度
* @returns {number}
*/
function getAllWidth() {
return document.documentElement.scrollWidth || document.body.scrollWidth;
}
/**
* 兼容获取页面的高度
* @returns {number}
*/
function getAllHeight() {
return document.documentElement.scrollHeight || document.body.scrollHeight;
}
function setStopPropagation(e) {
var evt = window.event || e;
return evt.stopPropagation ? evt.stopPropagation() : evt.cancelBubble = true;
}
<file_sep>/php/pay/selectaddress.php
<?php
@require_once("../config.php");
$userid = $_GET["userid"];
$sql = "select * from useraddress where userid = $userid";
$result = mysql_query($sql);
$item = mysql_fetch_array($result,MYSQL_ASSOC);
echo json_encode($item);
?><file_sep>/js/goods/balance.js
/**
* Created by 21213 on 2019/3/21.
*/
$(".common_header").load("../common/header.html", function () {
$.getScript("../../js/common/header.js");
});
$(".common_footer").load("../common/footer.html");
var price = 0;
var list = [];
//调用ajax获取该用户的商品列表
$.ajax({
type: "get",
url: "../../php/goods/getusershoppingcar.php",
data: {
type: 2,
userid: getCookie("userid")
},
dataType: "json",
success: function (obj) {
showGoods(obj);
}
});
function showGoods(obj) {
$(".balance_body").html("");
for (var i = 0; i < obj.length; i++) {
var item = obj[i];
$("<ul><li class='second_li'><img src='../../images/goods/" + item["goodsimg"] + ".png' alt='' class='goodsimg fl'/><p class='fl'>" + item["goodsname"] + "</p></li><li class='three_li'><p>" + item["goodssize"] + item["goodsstyle"] + "</p></li><li class='four_li'><span>" + item["num"] + "</span></li><li class='five_li'><p>" + item["goodsprice"] + ".00</p></li><li class='six_li'><p>" + item["goodsprice"] * item["num"] + ".00</p></li></ul>").appendTo($(".balance_body"));
price += item["goodsprice"] * item["num"];
list.push(item["id"]);
}
$(".balance_bottom_p").html("购物金额小计:¥:" + price + ".00");
$(".sumpay p").html("应付款金额:¥:" + price + ".00");
}
//获取收货人信息
$.ajax({
type: "get",
url: "../../php/pay/selectaddress.php",
data: {
userid: getCookie("userid")
},
dataType: "json",
success: function (obj) {
showAddress(obj);
}
});
function showAddress(obj) {
$("#address_name").html(obj["username"]);
$("#address_code").html(obj["userzipcode"]);
$("#address_phone").html(obj["userphone"]);
$("#address_msg").html(obj["useraddress"]);
}
$("#submit_buy").click(function () {
if ($(".balance_bottom_body .pay input").prop("checked") == true) {
$.ajax({
type: "get",
url: "../../php/pay/updateusergoods.php",
data: {
id: list.join(","),
type: 3
},
dataType: "json",
success: function (obj) {
if (obj["code"] == 1) {
window.location.href = "./topay.html?price=" + price;
} else {
setCookie("backUrl", window.location.href, 7);
window.location.href = "../login/retry.html";
}
}
});
}
});
<file_sep>/js/goods/topay.js
/**
* Created by 21213 on 2019/3/21.
*/
$(".common_header").load("../common/header.html", function () {
$.getScript("../../js/common/header.js");
});
$(".common_footer").load("../common/footer.html");
var price = window.location.search.split("=")[1];
$("#price").html(price + ".00元");<file_sep>/php/login/login.php
<?php
//调用公共的头部
@require_once("../config.php");
//获取传入的参数
$username = $_GET["username"];
$userpwd = $_GET["<PASSWORD>"];
//创建sql语句
$sql = "select * from userinfo where username = '$username' or usertel = '$username' or useremail = '$username'";
//执行sql语句
$result = mysql_query($sql);
//获取数据
$item = mysql_fetch_array($result,MYSQL_ASSOC);
$obj = array();
if($item){
$exitsPwd = $item["userpwd"];
if($exitsPwd == $userpwd){
$obj["code"] =1;
$obj["msg"] = "登录成功";
$obj["userid"] = $item["id"];
}else{
$obj["code"] = 0;
$obj["msg"] = "登录失败";
}
}else{
$obj["code"] = 0;
$obj["msg"] = "该用户名不存在";
}
echo json_encode($obj);
?><file_sep>/php/goods/getgoodsb2000count.php
<?php
//引入公共的config
@require_once("../config.php");
$price1 = $_GET["price1"];
$price2 = $_GET["price2"];
//创建sql语句
$sql = "SELECT count(*) as count from goodsinfo WHERE goodsprice BETWEEN $price1 and $price2";
//执行sql语句
$result = mysql_query($sql);
//获取结果
$obj = mysql_fetch_array($result,MYSQL_ASSOC);
echo json_encode($obj);
?><file_sep>/js/login/login.js
/**
* Created by 21213 on 2019/3/21.
*/
//引入公共的头部和底部
$(".common_header").load("../common/header.html", function () {
$.getScript("../../js/common/header.js");
});
$(".common_footer").load("../common/footer.html");
//点击登录判断用户名和密码是否正确
$("#login").click(function () {
//获取用户名和密码
var username = $("#username").val();
var userpwd = $("#userpwd").val();
//调用ajax判断数据
$.ajax({
type: "get",
url: "../../php/login/login.php",
data: {
username: username,
userpwd: <PASSWORD>
},
dataType: "json",
success: function (obj) {
successTip(obj);
}
});
});
//封装函数,判断是否登录成功
function successTip(obj) {
if (obj["code"] == 1) {
if ($("#remember_me").prop("checked")) {
setCookie("userid", obj["userid"], 7);
} else {
setCookie("userid", obj["userid"]);
}
if (getCookie("backUrl") == "") {
window.location.href = "../../index.html";
} else {
window.location.href = getCookie("backUrl");
}
} else {
setCookie("tip", obj["msg"], 7);
setCookie("backUrl", window.location.href, 7);
window.location.href = "./retry.html";
}
}<file_sep>/php/login/register.php
<?php
//引入公共的配置文件
@require_once("../config.php");
//获取传入的参数
$username = $_GET["username"];
$userlovename = $_GET["userlovename"];
$usertel = $_GET["usertel"];
$useremail = $_GET["useremail"];
$userpwd = $_GET["userpwd"];
$sql = "select * from userinfo where username = '$username' or usertel = '$usertel' or useremail ='$useremail'";
$result = mysql_query($sql);
$obj = array();
if(mysql_fetch_array($result)){
$obj["code"] =0;
$obj["msg"] = "该手机号或用户名邮箱已被使用";
}else{
//创建sql语句
$sql1 = "insert into userinfo(username,userlovename,usertel,useremail,userpwd) values ('$username','$userlovename','$usertel','$useremail','$userpwd')";
//执行sql语句
mysql_query($sql1);
//获取上条sql语句受影响的行数
$count = mysql_affected_rows();
//判断是否插入成功
if($count>0){
//插入成功
$obj["code"] = 1;
$obj["msg"] = "注册成功";
}else{
//插入失败
$obj["code"] = 0;
$obj["msg"] = "注册失败";
}
}
echo json_encode($obj);
?><file_sep>/php/goods/buygoods.php
<?php
//引入公共的config
@require_once("../config.php");
//获取传入的数据
$userid = $_GET["userid"];
$goodsid = $_GET["goodsid"];
$goodssize = $_GET["goodssize"];
$goodsstyle = $_GET["goodsstyle"];
//查看该用户是否买过这件商品
$sql = "select * from usergoods where userid = $userid and goodsid = $goodsid and type = 1";
//创建SQL语句
//执行sql语句
$result = mysql_query($sql);
if(mysql_fetch_array($result)){
$sql1 = "update usergoods set num = num+1 where userid = $userid and goodsid = $goodsid";
}else{
$sql1 = "insert into usergoods (userid,goodsid,num,goodssize,goodsstyle) values ($userid,$goodsid,1,'$goodssize','$goodsstyle')";
}
mysql_query($sql1);
//获取上条sql语句受影响的行数
$count = mysql_affected_rows();
//判断是否添加成功
$obj = array();
if($count>0){
$obj["code"]=1;
$obj["msg"] ="添加成功";
}else{
$obj["code"] =0;
$obj["msg"] ="网络繁忙,请稍后再试!";
}
echo json_encode($obj);
?><file_sep>/php/goods/getgoodslacecount.php
<?php
//引入公共的config
@require_once("../config.php");
//创建sql语句
$sql = "select count(*) as count from goodsinfo where type=2";
//执行sql语句
$result = mysql_query($sql);
//获取结果
$obj = mysql_fetch_array($result,MYSQL_ASSOC);
echo json_encode($obj);
?><file_sep>/js/common/page.js
/**
* Created by 21213 on 2019/3/8.
*/
function Page(ele, json) {
this.target = document.querySelector(ele);
this.pageIndex = 1;
this.data = {
"next": "下一页",
"prev": "上一页",
"dataCount": 100,
"showNum": 5,
"showPage": 5,
"callback": function (pageIndex) {
}
};
this.extend(json);
this.create();
this.bindData();
}
Page.prototype.extend = function (json) {
Object.assign(this.data, json);
};
Page.prototype.bindEvent = function () {
var that = this;
this.prevBtn.className = "page_prev";
this.nextBtn.className = "page_next";
this.prevBtn.onclick = function () {
that.pageIndex--;
that.bindData();
};
this.nextBtn.onclick = function () {
that.pageIndex++;
that.bindData();
};
};
Page.prototype.bindData = function () {
var that = this;
var maxPageIndex = Math.ceil(this.data["dataCount"] / this.data["showNum"]);
var midlleIndex = Math.floor(this.data["showPage"] / 2);
var start = 1;
var end = this.data["showPage"] > maxPageIndex ? maxPageIndex : this.data["showPage"];
if (this.pageIndex > midlleIndex) {
start = this.pageIndex - midlleIndex;
end = this.pageIndex + midlleIndex;
}
if (this.pageIndex > maxPageIndex - midlleIndex) {
start = maxPageIndex - this.data["showPage"] + 1;
end = maxPageIndex;
}
start = start < 1 ? 1 : start;
this.content.innerHTML = "";
for (var i = start; i <= end; i++) {
var li = document.createElement("li");
li.innerHTML = i;
if (i == this.pageIndex) {
li.className = "selected";
}
this.content.appendChild(li);
li.onclick = function () {
that.pageIndex = this.innerHTML * 1;
that.bindData();
};
}
this.bindEvent();
if (this.pageIndex == maxPageIndex) {
this.nextBtn.onclick = null;
this.nextBtn.className = "page_next disabled";
}
if (this.pageIndex == 1) {
this.prevBtn.onclick = null;
this.prevBtn.className = "page_prev disabled";
}
if (this.data["callback"]) {
this.data["callback"](this.pageIndex);
}
};
Page.prototype.create = function () {
this.target.className = "box";
this.prevBtn = document.createElement("span");
this.prevBtn.className = "page_prev";
this.prevBtn.innerHTML = this.data["prev"];
this.target.appendChild(this.prevBtn);
this.content = document.createElement("ul");
this.content.className = "page_content";
this.target.appendChild(this.content);
this.nextBtn = document.createElement("span");
this.nextBtn.className = "page_next";
this.nextBtn.innerHTML = this.data["next"];
this.target.appendChild(this.nextBtn);
};
<file_sep>/php/config.php
<?php
//公用数据库连接
@header("content-type:text/html:charset=utf-8");
@header("Access-Control-Allow-Origin:*");
//创建数据库连接
$conn = @mysql_connect("localhost","root","root");
//指定访问的表
mysql_select_db("crazy",$conn);
//指定编码格式
mysql_query("set names utf8");
?><file_sep>/php/pay/updateusergoodstype.php
<?php
//引入公共的config.php文件
@require_once("../config.php");
//获取数据id
$id = $_GET["id"];
$type = $_GET["type"];
//创建sql语句
$sql = "update usergoods set type = $type where id = $id";
//执行sql语句
mysql_query($sql);
//获取上一条sql语句影响的条数
$count = mysql_affected_rows();
$obj = array();
if($count>0){
$obj["code"] =1;
$obj["msg"]="提交订单成功";
}else{
$obj["code"] =0;
$obj["msg"] = "网络繁忙,请稍后重试!";
}
echo json_encode($obj);
?><file_sep>/php/pay/addaddress.php
<?php
//调用公共的config.php文件
@require_once("../config.php");
//获取用户传入的数据
$userid = $_GET["userid"];
$username = $_GET["username"];
$userphone = $_GET["userphone"];
$useraddress = $_GET["useraddress"];
$userzipcode = $_GET["userzipcode"];
$usertel = $_GET["usertel"];
$sql = "select * from useraddress where userid = $userid";
//执行sql语句
$result = mysql_query($sql);
$item = mysql_fetch_array($result);
$obj = array();
if(!$item){
//创建sql插入数据
$sql1 = "insert into useraddress (userid,username,userphone,useraddress,userzipcode,usertel) values ($userid,'$username',$userphone,'$useraddress',$userzipcode,$usertel)";
mysql_query($sql1);
//获取上一条sql语句影响的行数
$count = mysql_affected_rows();
//判断结果
if($count>0){
$obj["code"] =1;
$obj["msg"]="创建成功!";
}else{
$obj["code"] =0;
$obj["msg"]="网络繁忙,请稍后重试!";
}
}
echo json_encode($obj);
?><file_sep>/js/goods/detail.js
/**
* Created by 21213 on 2019/3/21.
*/
//引入公共的部分
$(".common_header").load("../common/header.html", function () {
$.getScript("../../js/common/header.js");
});
$(".common_footer").load("../common/footer.html");
//获取地址框的id值
var id = window.location.search.split("=")[1];
//调用ajax获取商品详情信息
$.ajax({
type: "get",
url: "../../php/goods/detail.php",
data: {
id: id
},
dataType: "json",
success: function (obj) {
showData(obj);
}
});
function showData(obj) {
var obj = obj[0];
if (obj["code"] == 0) {
setCookie(tip, obj["msg"], 7);
window.location.href = "../login.retry.html";
} else {
$(".goodsname").html(obj["goodsname"]);
$(".tip_detail_body p").html("商品名称:" + obj["goodsname"]);
$(".detail_body_centent_left img").attr("src", "../../images/goods/" + obj["goodsimg"] + ".png");
$(".tip_detail_body img").attr("src", "../../images/goods/" + obj["goodsimg"] + ".png");
$(".detail_body_centent_left #big_shadow img").attr("src", "../../images/goods/" + obj["goodsimg"] + ".png");
$(".detail_body_centent_right h3").html(obj["goodsname"]);
$(".detail_body_centent_right .xl").html("购买指数:" + obj["buynum"]);
$(".detail_body_centent_right .weight").html(obj["goodsstyle"] + "约:" + obj["goodsweight"]);
$(".detail_body_centent_right .price").html("¥" + obj["goodsprice"] + ".00");
var style = obj["goodsstyle"].split(",");
var size = obj["goodssize"].split(",");
var html1 = "";
var html2 = "";
$("#goodsstyle").html("");
$("#goodssize").html("");
for (var i = 0; i < style.length; i++) {
html1 += "<option value=" + style[i] + ">" + style[i] + "</option>";
}
for (var j = 0; j < size.length; j++) {
html2 += "<option value=" + size[j] + ">" + size[j] + "</option>";
}
$(html1).appendTo($("#goodsstyle"));
$(html2).appendTo($("#goodssize"));
}
}
//获取遮罩层最大x和y值
var maxX = $(".detail_body_centent_left").width() - $("#small_shadow").width();
var maxY = $(".detail_body_centent_left").height() - $("#small_shadow").height();
//鼠标进入显示遮罩层,鼠标离开隐藏遮罩层
$(".detail_body_centent_left").mouseenter(function (e) {
$("#small_shadow").show();
$("#big_shadow").show();
//获取鼠标进入的位置
var evt = window.event || e;
var startX = evt.clientX * 1 + getScrollLeft();
var startY = evt.clientY * 1 + getScrollTop();
//获取盒子距离上面和左边的距离
$(document).mousemove(function (e) {
//获取鼠标移动的位置
var evt = window.event || e;
var endX = evt.clientX * 1 + getScrollLeft();
var endY = evt.clientY * 1 + getScrollTop();
$("#small_shadow").css({
left: startX - $(".detail_body_centent_left")[0].offsetLeft,
top: startY - $(".detail_body_centent_left")[0].offsetTop
});
//计算鼠标移动的距离
var moveX = endX - startX;
var moveY = endY - startY;
//设置遮罩层的临界值
//获取遮罩层的x和y
var shadowX = $("#small_shadow").css("left");
var shadowY = $("#small_shadow").css("top");
x = parseInt(shadowX) * 1 + moveX - $("#small_shadow").width() / 2;
y = parseInt(shadowY) * 1 + moveY - $("#small_shadow").height() / 2;
if (x >= maxX) {
x = maxX;
}
if (x <= 0) {
x = 0;
}
if (y >= maxY) {
y = maxY;
}
if (y <= 0) {
y = 0;
}
$("#small_shadow").css({
left: x,
top: y
});
$("#big_shadow img").css({
left: -x * 2,
top: -y * 2
});
});
}).mouseleave(function () {
$("#small_shadow").hide();
$("#big_shadow").hide();
$(document).unbind("mousemove");
});
//点击加入购物车按钮加入购物车
//判断 用户是否登录
//登录加入购物车
$("#add_car").click(function () {
//调用ajax存入数据
if (getCookie("userid")) {
$.ajax({
type: "get",
url: "../../php/goods/buygoods.php",
data: {
userid: getCookie("userid"),
goodsid: id,
goodssize: $("#goodssize").val(),
goodsstyle: $("#goodsstyle").val()
},
dataType: "json",
success: function (obj) {
successAdd(obj);
}
});
} else {
//没有登录跳转到登录界面
setCookie("backUrl", window.location.href, 7);
window.location.href = "../login/login.html";
}
});
$("#add_buy").click(function () {
if (getCookie("userid")) {
$.ajax({
type: "get",
url: "../../php/goods/buygoods.php",
data: {
userid: getCookie("userid"),
goodsid: id,
goodssize: $("#goodssize").val(),
goodsstyle: $("#goodsstyle").val()
},
dataType: "json",
success: function (obj) {
successBuy(obj);
}
});
} else {
//没有登录跳转到登录界面
setCookie("backUrl", window.location.href, 7);
window.location.href = "../login/login.html";
}
});
function successAdd(obj) {
if (obj["code"] == 0) {
setCookie("tip", obj["msg"], 7);
window.location.href = "../login/retry.html";
} else {
$(".tip_box").show();
$("#result").click(function () {
window.location.href = "./shoppingcar.html";
});
}
}
function successBuy(obj) {
if (obj["code"] == 0) {
setCookie("tip", obj["msg"], 7);
window.location.href = "../login/retry.html";
} else {
window.location.href = "./shoppingcar.html";
}
}
$(".detial_tip h3 span").click(function () {
$(".tip_box").hide();
});
$("#close").click(function () {
$(".tip_box").hide();
});
<file_sep>/php/goods/reviseusergoodsnum.php
<?php
//调用公共的config.php
@require_once("../config.php");
//获取传入的购物车id
$carId = $_GET["carId"];
$num = $_GET["num"];
//创建sql语句
$sql = "update usergoods set num = num+$num where id = $carId";
//执行sql语句
mysql_query($sql);
//查看上一条sql语句受影响的行数
$count = mysql_affected_rows();
//判断是否修改成功
$obj = array();
if($count>0){
$obj["code"] =1;
$obj["msg"] = "增加成功";
}else{
$obj["code"] = 0;
$obj["msg"] = "网络繁忙,请稍后再试";
}
echo json_encode($obj);
?><file_sep>/js/login/information.js
/**
* Created by 21213 on 2019/3/21.
*/
$(".common_header").load("../common/header.html", function () {
$.getScript("../../js/common/header.js");
});
$(".common_footer").load("../common/footer.html");
$.ajax({
type: "get",
url: "../../php/goods/getusershoppingcar.php",
data: {
type: 3,
userid: getCookie("userid")
},
dataType: "json",
success: function (obj) {
showGoods(obj);
}
});
function showGoods(obj) {
$(".xq").html("");
for (var i = 0; i < obj.length; i++) {
var item = obj[i];
$("<ul><li class='second_li'><img src='../../images/goods/" + item["goodsimg"] + ".png' alt='' class='goodsimg fl'/><p class='fl'>" + item["goodsname"] + "</p></li><li class='three_li'><p>" + item["goodsprice"] * item["num"] + ".00</p></li><li class='four_li'><span>" + item["num"] + "</span></li><li class='five_li'><p>待付款</p></li><li class='six_li'><p><a href='../goods/topay.html?price=" + item["goodsprice"] * item["num"] + "'>去付款</a><button class='cancle_dd' data_id=" + item["id"] + ">取消订单</button></p></li></ul>").appendTo($(".xq"));
}
}
$(".user_select li.selected").index();
$(".user_select li").click(function () {
$(".user_select li").each(function () {
$(this).removeClass("selected");
});
$(this).addClass("selected");
tbshow();
});
function tbshow() {
var index = $(".user_select li.selected").index();
$(".series>li").each(function () {
$(this).removeClass("selected");
});
$(".series>li").eq(index).addClass("selected");
}
$(".user_select_exit").click(function () {
setCookie("backUrl", "", -7);
setCookie("userid", "", -7);
window.location.href = "./login.html";
});
$("#replace").click(function () {
var userpwdReg = /^[a-z0-9._]{6,12}$/ig;
if ($("#newuserpwd1").val() == $("#newuserpwd2").val()) {
if (userpwdReg.test($("#newuserpwd1").val())) {
$.ajax({
type: "get",
url: "../../php/login/updateuser.php",
data: {
userid: getCookie("userid"),
userpwd: $("#newuserpwd1").val()
},
dataType: "json",
success: function (obj) {
if (obj["code"] == 1) {
$(".g").hide();
$(".t").show();
} else {
setCookie("backUrl", window.location.href, 7);
window.location.href = "./retry.html";
}
}
});
} else {
$("#newuserpwd1").css("color", "red");
}
} else {
$("#newuserpwd1").css("color", "red");
}
});
$(document).on("click", ".cancle_dd", function () {
$.ajax({
type: "get",
url: "../../php/pay/updateusergoodstype.php",
data: {
type: 0,
id: $(this).attr("data_id")
},
dataType: "json",
success: function (obj) {
if (obj["code"] == 1) {
window.location.reload();
}
}
});
});<file_sep>/php/goods/detail.php
<?php
//引入公共的config配置文件
@require_once("../config.php");
//接受传入的参数
$id = $_GET["id"];
//创建sql语句
$sql = "select * from goodsinfo where id = $id";
//执行sql语句
$result = mysql_query($sql);
//获取数据
$item = mysql_fetch_array($result,MYSQL_ASSOC);
$obj = array();
//判断数据是否找到
if($item){
$obj[] = $item;
}else{
//没有找到数据
$obj["code"] = 0;
$obj["msg"] = "您访问的数据不存在?";
}
echo json_encode($obj);
?><file_sep>/js/index/index.js
/**
* Created by 21213 on 2019/3/21.
*/
//导航图注册事件
var index = 0;
var timeId = bannerShow(index);
$("#index_banner_nav li").mouseenter(function () {
clearInterval(timeId);
index = $(this).index();
$(this).addClass("selected").siblings().removeClass("selected");
$("#index_banner_content li").eq(index).addClass("selected").siblings().removeClass("selected");
}).mouseleave(function () {
timeId = bannerShow(index);
});
$(".index_banner").mouseenter(function () {
clearInterval(timeId);
$(".index_banner_left").stop(true, false).show();
$(".index_banner_right").stop(true, false).show();
}).mouseleave(function () {
$(".index_banner_left").stop(true, false).hide();
$(".index_banner_right").stop(true, false).hide();
timeId = bannerShow(index);
});
$(".index_banner_left").click(function () {
clearInterval(timeId);
$("#index_banner_nav li").each(function () {
if ($(this).hasClass("selected")) {
$("#index_banner_nav li").each(function () {
$(this).removeClass("selected");
});
$("#index_banner_content li").each(function () {
$(this).removeClass("selected");
});
var abc = $(this).index();
abc = abc - 1;
if (index < 0) {
abc = $("#index_banner_nav li").length - 1;
}
$("#index_banner_nav li").eq(abc).addClass("selected");
$("#index_banner_content li").eq(abc).addClass("selected");
return false;
}
});
});
$(".index_banner_right").click(function () {
clearInterval(timeId);
$("#index_banner_nav li").each(function () {
if ($(this).hasClass("selected")) {
$("#index_banner_nav li").each(function () {
$(this).removeClass("selected");
});
$("#index_banner_content li").each(function () {
$(this).removeClass("selected");
});
var abc = $(this).index();
abc = abc + 1;
if (abc > $("#index_banner_nav li").length - 1) {
abc = 0;
}
console.log(abc);
$("#index_banner_nav li").eq(abc).addClass("selected");
$("#index_banner_content li").eq(abc).addClass("selected");
return false;
}
});
});
function bannerShow(index) {
clearInterval(timeId);
timeId = setInterval(function () {
index++;
if (index >= ($("#index_banner_nav li").length)) {
index = 0;
}
if (index < 0) {
index = $("#index_banner_nav li").length - 1;
}
$("#index_banner_nav li").eq(index).addClass("selected").siblings().removeClass("selected");
$("#index_banner_content li").eq(index).addClass("selected").siblings().removeClass("selected");
}, 1500);
return timeId;
}
//点击登录,跳转到登录界面
$(document).on("click", "#header_username_login", function () {
setCookie("backUrl", window.location.href, 7);
window.location.href = "./html/login/login.html";
});
//点击注册,跳转到注册界面
$(document).on("click", "#header_username_register", function () {
setCookie("backUrl", window.location.href, 7);
window.location.href = "./html/login/register.html";
});
//登录成功到达这个页面显示用户名
if (getCookie("userid")) {
$.ajax({
type: "get",
url: "./php/index/selectuser.php",
data: {
userid: getCookie("userid")
},
dataType: "json",
success: function (obj) {
showUser(obj);
}
});
}
//封装函数显示用户信息
function showUser(obj) {
$(".header_one").html("<a href='./html/login/information.html'>" + obj["username"] + "</a><a href='#' class='exit'> /注销 </a>")
}
//为注销按钮绑定事件
$(document).on("click", ".exit", function () {
setCookie("backUrl", "", -7);
setCookie("userid", "", -7);
window.location.reload();
});
<file_sep>/php/index/selectuser.php
<?php
//引入公共的文件
@require_once("../config.php");
//获取传入的参数
$userid = $_GET["userid"];
//创建sql语句
$sql = "select * from userinfo where id = $userid";
//执行sql语句
$result = mysql_query($sql);
//获取结果
$item = mysql_fetch_array($result,MYSQL_ASSOC);
$item["userpwd"] = "";
echo json_encode($item);
?><file_sep>/php/login/updateuser.php
<?php
//引入公共的配置文件
@require_once("../config.php");
//获取传入的参数
$userid = $_GET["userid"];
$userpwd = $_GET["<PASSWORD>"];
//创建sql语句
$sql = "update userinfo set userpwd = <PASSWORD>' where id = $userid";
//执行sql语句
mysql_query($sql);
//获取上条sql语句受影响的行数
$count = mysql_affected_rows();
//判断是否插入成功
$obj = array();
if($count>0){
//插入成功
$obj["code"] = 1;
$obj["msg"] = "修改成功";
}else{
//插入失败
$obj["code"] = 0;
$obj["msg"] = "网络繁忙,请稍后重试!";
}
echo json_encode($obj);
?><file_sep>/php/goods/delusergoods.php
<?php
//引入公共的config.php文件
@require_once("../config.php");
//获取数据id
$id = $_GET["goodid"];
//创建sql语句
$sql = "delete from usergoods where id in ($id)";
//执行sql语句
mysql_query($sql);
//获取上一条sql语句影响的条数
$count = mysql_affected_rows();
$obj = array();
if($count>0){
$obj["code"] =1;
$obj["msg"]="删除成功";
}else{
$obj["code"] =0;
$obj["msg"] = "网络繁忙,请稍后重试!";
}
echo json_encode($obj);
?><file_sep>/php/goods/getusershoppingcar.php
<?php
//引入公共的config.php
@require_once("../config.php");
//获取传入的参数
$userid = $_GET["userid"];
$type =$_GET["type"];
//创建sql语句
$sql = "SELECT us.id,gd.goodsname,gd.goodsimg,gd.goodsprice,us.goodsid,us.num,us.goodssize,us.goodsstyle from usergoods us, goodsinfo gd where us.goodsid = gd.id and us.userid = $userid and us.type =$type";
//执行sql语句
$result = mysql_query($sql);
//获取结果
$obj = array();
while($itme = mysql_fetch_array($result,MYSQL_ASSOC)){
$obj[] = $itme;
}
echo json_encode($obj);
?><file_sep>/js/goods/pay.js
/**
* Created by 21213 on 2019/3/21.
*/
$(".common_header").load("../common/header.html", function () {
$.getScript("../../js/common/header.js");
});
$(".common_footer").load("../common/footer.html");
//构建省市联动 //数据获取地址:http://api.yytianqi.com/citylist/id/3
//调用ajax获取数据
$.ajax({
type: "get",
url: "http://api.yytianqi.com/citylist/id/2",
dataType: "json",
success: function (obj) {
//获取国家的id和name
var countryName = obj["name"];
var countryId = obj["city_id"];
//创建国家列表
$("<option value=" + countryId + ">" + countryName + "</option>").appendTo($("#country"));
$("#country").change(function () {
$("#provice").html("<option value=''>请选择省份</option>");
$("#city").html("<option value=''>请选择城市</option>");
$("#town").html("<option value=''>请选择区县</option>");
if ($(this).val() != "") {
//获取省份列表
proviceList = obj["list"];
//循环创建省份
for (var i = 0; i < proviceList.length; i++) {
var item = proviceList[i];
$("<option value=" + item["city_id"] + ">" + item["name"] + "</option>").appendTo($("#provice"));
}
}
$("#provice").change(function () {
$("#city").html("<option value=''>请选择城市</option>");
$("#town").html("<option value=''>请选择区县</option>");
//获取省份的id
var proviceId = $(this).val();
//获取省份
var provice = proviceList.filter(function (item) {
return item["city_id"] == proviceId;
})[0];
//获取城市的集合
cityList = provice["list"];
//循环创建元素
for (var i = 0; i < cityList.length; i++) {
var item = cityList[i];
$("<option value=" + item["city_id"] + ">" + item["name"] + "</option>").appendTo($("#city"));
}
$("#city").change(function () {
$("#town").html("<option value=''>请选择区县</option>");
//获取城市id
var cityId = $(this).val();
//获取城市
var city = cityList.filter(function (item) {
return item["city_id"] == cityId;
})[0];
//获取区县的集合
if (city["list"] != undefined) {
var townList = city["list"];
for (var i = 0; i < townList.length; i++) {
var item = townList[i];
$("<option value=" + item["city_id"] + ">" + item["name"] + "</option>").appendTo($("#town"));
}
}
});
});
});
}
});
//点击提交按钮保存收货地址
$("#submit_address").click(function () {
//获取地址
var address = $("#country").find("option:selected").text() + $("#provice").find("option:selected").text() + "省" + $("#city").find("option:selected").text() + "市" + ($("#town").val() == "" ? "" : $("#town").find("option:selected").text()) + "(区,县,镇)" + $("#address_xmsg").val();
//调用ajax写入数据
$.ajax({
type: "get",
url: "../../php/pay/addaddress.php",
data: {
userid: getCookie("userid"),
username: $("#address_name").val(),
userphone: $("#address_phone").val(),
useraddress: address,
userzipcode: $("#address_yb").val(),
usertel: $("#address_tel").val()
},
dataType: "json",
success: function (obj) {
successAdd(obj)
}
});
});
function successAdd(obj) {
if (obj["code"] == 0) {
setCookie("backUrl", window.location.href, 7);
window.location.href = "../login/retry.html";
} else {
//调用ajax修改商品信息
window.location.href = "./balance.html";
//$.ajax({
// type: "get",
// url: "../../php/pay/updateusergoods.php",
// data: {
// userid: getCookie("userid"),
// type: 2
// },
// dataType: "json",
// success: function (obj) {
// if (obj["code"] == 1) {
// window.location.href = "./balance.html";
// } else {
// setCookie("backUrl", window.location.href, 7);
// window.location.href = "../login/retry.html";
// }
// }
//});
}
}
//调用ajax获取存储地址
$.ajax({
type: "get",
url: "../../php/pay/selectaddress.php",
data: {
userid: getCookie("userid")
},
dataType: "json",
success: function (obj) {
//显示地址
showExitsAddress(obj);
}
});
function showExitsAddress(obj) {
if (obj) {
var country = obj["useraddress"].substring(0, obj["useraddress"].indexOf("国") + 1);
var provice = obj["useraddress"].substring(obj["useraddress"].indexOf("国") + 1, obj["useraddress"].indexOf("省") + 1);
var city = obj["useraddress"].substring(obj["useraddress"].indexOf("省") + 1, obj["useraddress"].indexOf("市") + 1);
var town = obj["useraddress"].substring(obj["useraddress"].indexOf("市") + 1, obj["useraddress"].indexOf("镇)") + 2);
var xx = obj["useraddress"].substring(obj["useraddress"].indexOf("镇)") + 2, obj["useraddress"].length);
$("#address_name").val(obj["username"]);
$("#address_phone").val(obj["userphone"]);
$("#address_yb").val(obj["userzipcode"]);
$("#address_tel").val(obj["usertel"]);
$("#country option").html(country);
$("#provice option").html(provice);
$("#city option").html(city);
$("#town option").html(town);
$("#address_xmsg").val(xx);
}
}
<file_sep>/js/common/header.js
//为导航栏礼物设置鼠标移动显示或隐藏下拉框
$("#gift").mouseenter(function () {
$(".header_li_gift_show").stop(true, false).toggle(300);
$("#gift_list02 dd").mouseenter(function () {
var index = $(this).index();
$("#gift_show_img li").eq(index - 1).addClass("selected").siblings().removeClass("selected");
});
}).mouseleave(function () {
$(".header_li_gift_show").stop(true, false).toggle(300);
});
//为导航栏婚戒设置鼠标移动显示或隐藏下拉框
$("#ring").mouseenter(function () {
$(".header_li_gift_show1").stop(true, false).toggle(300);
$("#gift_list01 dd").mouseenter(function () {
var index = $(this).index();
$("#ring_img li").eq(index - 1).addClass("selected").siblings().removeClass("selected");
});
}).mouseleave(function () {
$(".header_li_gift_show1").stop(true, false).toggle(300);
});
//为导航栏真爱定制设置鼠标移动显示和隐藏
$("#custom_li").mouseenter(function () {
$(".header_li_gift_show2").stop(true, false).toggle(300);
}).mouseleave(function () {
$(".header_li_gift_show2").stop(true, false).toggle(300);
});
//登录成功到达这个页面显示用户名
if (window.location.href != "http://localhost/jewelry/") {
if (getCookie("userid")) {
$.ajax({
type: "get",
url: "../../php/index/selectuser.php",
data: {
userid: getCookie("userid")
},
dataType: "json",
success: function (obj) {
showUser(obj);
}
});
}
}
//封装函数显示用户信息
function showUser(obj) {
$(".header_one").html("<a href='../login/information.html'>" + obj["username"] + "</a><a href='#' class='exit'> /注销 </a>")
}
//为注销按钮绑定事件
$(document).on("click", ".exit", function () {
setCookie("backUrl", "", -7);
setCookie("userid", "", -7);
window.location.reload();
});
$(document).scroll(function () {
if ($(document).scrollTop() >= $(".header").height()) {
$(".header_nav").css({
position: "fixed",
top: "0",
left: "0",
backgroundColor: "black"
});
$(".header_nav li").css("color", "#FFF");
$(".common_header").css("paddingBottom", $(".header").height());
} else {
$(".header_nav").css({
width: "100%",
height: "67px",
backgroundColor: "#ffffff",
position: "relative",
Zindex: "999"
});
$(".header_nav li").css("color", "#000");
$(".common_header").css("paddingBottom", 0);
}
}
);
<file_sep>/js/goods/choiseries.js
/**
* Created by 21213 on 2019/3/21.
*/
var showNum = 12;
var pageIndex = 1;
//引入公共头部和底部
$(".common_header").load("../common/header.html", function () {
$.getScript("../../js/common/header.js");
});
$(".common_footer").load("../common/footer.html");
getData(pageIndex, showNum);
//调用ajax获取后台商品数据
function getData(pageIndex, showNum) {
$.ajax({
type: "get",
url: "../../php/goods/selectgoodschoiseries.php",
data: {
jumpData: (pageIndex - 1) * showNum,
showData: showNum
},
dataType: "json",
success: function (obj) {
showGoods(obj);
}
});
}
//封装函数显示商品
function showGoods(obj) {
$(".handseries_body_content").html("");
for (var i = 0; i < obj.length; i++) {
var goods = obj[i];
$("<li class='goods_click' data_id='" + goods["id"] + "'><img src='../../images/goods/" + goods["goodsimg"] + ".png' /><a href='#'>" + goods["goodsname"] + "¥" + goods["goodsprice"] + "</a></li>").appendTo($(".handseries_body_content"));
}
}
//调用函数显示总条数
showGoodsCount();
function showGoodsCount() {
$.ajax({
type: "get",
url: "../../php/goods/getgoodschoiseriescount.php",
dataType: "json",
success: function (obj) {
showNumPage(obj);
}
});
}
//封装函数显示总商品数和翻页
function showNumPage(obj) {
$("<p class='p1'>总计" + obj["count"] + "个真爱礼物 <div id='box'></div></p>").appendTo($(".handseries_body .w"));
update(obj);
}
//封装函数更新页码
function update(obj) {
var page = new Page("#box", {
"next": "下一页",
"prev": "上一页",
"dataCount": obj["count"],
"showNum": showNum,
"showPage": 5,
"callback": function (pageIndex) {
getData(pageIndex, showNum);
}
});
}
//为所有的li绑定点击事件
$(document).on("click", ".goods_click", function () {
window.location.href="./detail.html?id="+$(this).attr("data_id");
});
<file_sep>/php/goods/selectgoodsb2000.php
<?php
//引入公共的文件
@require_once("../config.php");
//获取传入的数据
$jumpData = $_GET["jumpData"];
$showData = $_GET["showData"];
$price1 = $_GET["price1"];
$price2 = $_GET["price2"];
//创建sql语句
$sql = "SELECT * from goodsinfo WHERE goodsprice BETWEEN $price1 and $price2 ORDER BY goodsprice ASC limit $jumpData,$showData";
//执行sql语句
$result = mysql_query($sql);
//循环拿到数据
$obj = array();
while($item = mysql_fetch_array($result,MYSQL_ASSOC)){
$obj[] = $item;
}
echo json_encode($obj);
?>
|
0241f0a5418b4e97d9c8a90e62adccf221eb802e
|
[
"JavaScript",
"PHP"
] | 27
|
JavaScript
|
crazyfengyu/jewelry
|
9c4c9d10217219b44d76fd7808422c5cec42fc4c
|
49826f66bfb9eacda13bb429feb90d033168b622
|
refs/heads/master
|
<repo_name>ssathy2/siddsathyam_meteor<file_sep>/server/app.js
if (Meteor.isServer) {
Meteor.startup(function () {
// bootstrap the admin user if they exist -- You'll be replacing the id later
if (Meteor.users.findOne("3M5Wjc9tZuiQxx87P"))
console.log(Roles.addUsersToRoles("3M5Wjc9tZuiQxx87P", ['admin', 'blogAdmin']));
});
}<file_sep>/client/js/meteor_routes.js
Router.configure({
layoutTemplate: 'masterLayout',
notFoundTemplate: '404Page'
});
Router.route('/', function() {
this.render('aboutTemplate');
});
Router.route('/signin', function () {
this.render('signinTemplate');
});
Router.route('/projects', function () {
this.render('projectsTemplate');
});
Router.route('/about', function () {
this.render('aboutTemplate');
});
<file_sep>/client/js/app.js
Template.registerHelper('formatDate', function(date) {
return moment(date).format('MMMM Do YYYY [at] h:mm a');
});
Template.registerHelper('log', function(data) {
console.log(data);
});<file_sep>/server/server_blog.js
// JavaScript
if (Meteor.isServer) {
Blog.config({
adminRole: 'blogAdmin',
authorRole: 'blogAuthor'
});
}<file_sep>/client/js/blog.js
if (Meteor.isClient) {
Blog.config({
blogIndexTemplate: 'blogIndexTemplate',
blogShowTemplate: 'blogPostDetailTemplate'
});
Blog.config({
comments: {
disqusShortname: 'siddsathyam'
}
});
}
Blog.config({
syntaxHighlighting: true,
syntaxHighlightingTheme: 'github'
});
|
338cecc675b815baf7744854128c069c64d66249
|
[
"JavaScript"
] | 5
|
JavaScript
|
ssathy2/siddsathyam_meteor
|
633b137e2eafa06b53f17adab16c6569bfd13d63
|
f353da517b0cf6593e37cb71ae9f44ed96e39e1e
|
refs/heads/master
|
<file_sep>#!/bin/sh
# run flink job
exec flink run /app.jar > /app.out &
exit 0
<file_sep># Flink on Kubernetes.
**Flink achitecture**
<ul>
<li>One active JobManager(JM) </li>
<li>Several TaskManagers(TM)</li>
</ul>
**One job per cluster**
<ul>
<li>Evolving job deployment philosophy</li>
<li>Tie cluster lifecycle to job lifecycle)</li>
<li>Ideally, the job is first-class.<br>
(think about running a job on a platform like Kubernetes,
not a running Flink cluster first then submitting the job)</li>
</ul>
**Flink-on-K8s**
<ul>
<li>JobManager Deployment(jobmanager-deployment.yaml)
<ul>
<li>maintain 1 replica of Flink container running as a JM </li>
<li>apply a label like "flink-jobmanager"</li>
<li>Jobmanager uses custom Flink Docker image "afilichkin/flink-k8s-with-submit-job" , it start JM and also submit the "app.jar"
</ul>
</li>
<li>JM service(jobmanager-service.yaml)
<ul>
<li>make JobManager accessiable by a hostname & port</li>
<li>select pods with labebl "flink-jobmanager"</li>
</ul>
</li>
<li>TaskManager Deployment(taskmanager-deployment.yaml)
<ul>
<li>maintain n replica of Flink container running as a TM </li>
</ul>
</li>
</ul>
**custom Flink Docker image "afilichkin/flink-k8s-with-submit-job" has only one change in "docker-entrypoint-custom.sh":**
#Customization start
#fix for https://issues.apache.org/jira/browse/FLINK-9937
echo " 127.0.0.1 ${JOB_MANAGER_RPC_ADDRESS}" >> /etc/hosts
echo "Submit flink job in background"
exec /submit-flink-job.sh &
#Customization end
# Main flow
<img src="flow.jpg" width=800/>
# flink-k8s: Flink image that can work with Kubernetes.
Flink image for Kubernetes that fixes Jobmanage connection issue
https://issues.apache.org/jira/browse/FLINK-9937
You can use afilichkin/flink-k8s in jobmanager-deployment.yaml file
docker-entrypoint-custom.sh has only one change:
echo " 127.0.0.1 ${JOB_MANAGER_RPC_ADDRESS}" >> /etc/hosts
|
008100512dc9d82648167d618c46dad066ab8543
|
[
"Markdown",
"Shell"
] | 2
|
Shell
|
guozhongtao/flink-k8s
|
53422c5677148f8b1e46ccd20072e7bcdc37abc8
|
cc48381f271b2e4eac1717f70628e295f7158e67
|
refs/heads/master
|
<repo_name>helmelix/rss_react_redux<file_sep>/src/routes/channel/containers/channel.js
import { connect } from 'react-redux'
import { fetchChannel, fetchChannelNews, selectNews, cleanSelectedData} from '../modules/channel'
import Channel from '../components/channel'
function mapStateToProps(state) {
return {
newsList: state.channel.newsList,
selectedChannel: state.channel.selectedChannel,
selectedNews: state.channel.selectedNews,
pieChartData: state.channel.pieChartData,
newsAmount: state.channel.newsAmount,
parceChannelFail: state.channel.parceChannelFail
};
}
const mapDispatchToProps = {
fetchChannelNews: (url) => fetchChannelNews(url),
fetchChannel: (ch_id) => fetchChannel(ch_id),
selectNews: (news) => selectNews(news),
cleanSelectedData: () => cleanSelectedData()
}
export default connect(mapStateToProps, mapDispatchToProps)(Channel);
<file_sep>/src/routes/Home/components/HomeView.js
import React, { Component } from 'react'
import './HomeView.scss'
import { browserHistory} from 'react-router'
export class HomeView extends Component {
componentDidMount() {
browserHistory.push('/feeds')
}
render() {
return (
<div>
<h4>Welcome!</h4>
</div>
)
}
}
export default HomeView
<file_sep>/src/routes/channel/components/channel.js
import React, { PropTypes, Component } from 'react';
import isEqual from 'lodash/isEqual';
import { PieChart } from 'react-d3';
import { browserHistory} from 'react-router'
class Channel extends Component {
componentWillMount() {
this.props.fetchChannel(this.props.routeParams.channel_id)
.then((res) => {
this.props.fetchChannelNews(res.attributes.url)
})
}
componentWillReceiveProps(nextProps) {
if (!isEqual(this.props.routeParams.channel_id, nextProps.routeParams.channel_id)) {
this.props.fetchChannel(nextProps.routeParams.channel_id)
.then((res) => {
this.props.fetchChannelNews(res.attributes.url)
})
}
}
componentWillUnmount() {
this.props.cleanSelectedData();
}
render() {
return(
<div className="row">
<div className="col-md-6">
<div>
<h1 className="lead text-center">{this.props.selectedChannel.attributes.name}</h1>
<div className="space_bot">
<button className='btn btn-default' onClick={()=>{this.props.onDeleteChannel(this.props.routeParams.channel_id)
browserHistory.push('/feeds/')
}}>
Delete Channel
</button>
</div>
</div>
{!this.props.parceChannelFail ?
<div>
<ul className="list-group ">
{this.props.newsList.map(list =>
<li className="list-group-item list_pointer" key={Math.random()} onClick={()=>this.props.selectNews(list)}>
{list.title}
</li>)
}
</ul>
</div>
: <h4>Error receiving data</h4>}
</div>
<div className="col-md-6 space_top">
<div>
{this.props.selectedNews.title ?
<div>
<div>
<p className="lead">{this.props.selectedNews.title}</p>
</div>
<div dangerouslySetInnerHTML={{
__html: this.props.selectedNews.description
}} />
<div>
{this.props.selectedNews.pubDate ? this.props.selectedNews.pubDate : ''}
</div>
</div>
: <div></div>
}
</div>
<div>
{this.props.newsAmount ?
<div className="space_top">
<div>
number of channels: {this.props.channelsCount}
</div>
<div>
number of messages: {this.props.newsAmount}
</div>
{!this.props.pieChartData[0] ?<div>Latin letters not found</div>
: <div>characters appearance frequency:</div>}
<div>
<PieChart
data={this.props.pieChartData}
width={600}
height={600}
radius={150}
innerRadius={20}
sectorBorderColor="blue"
/>
</div>
</div>
: <div></div>
}
</div>
</div>
</div>
)
}
}
Channel.propTypes = {
fetchChannelNews: PropTypes.func.isRequired,
fetchChannel: PropTypes.func.isRequired,
selectNews: PropTypes.func.isRequired,
cleanSelectedData: PropTypes.func.isRequired,
newsList: PropTypes.array.isRequired,
selectedChannel: PropTypes.object.isRequired,
selectedNews: PropTypes.object.isRequired,
pieChartData: PropTypes.array.isRequired,
newsAmount: PropTypes.number.isRequired
}
export default Channel
<file_sep>/src/routes/feeds/components/FeedsList.js
import React, { PropTypes, Component } from 'react';
import AddForm from './form'
import { addChannel, addCount } from '../modules/feeds'
import { browserHistory, Link } from 'react-router'
class Feeds extends Component {
componentDidMount() {
this.props.fetchChannels();
}
render() {
return (
<div className="row">
<div className="col-md-3 space_left">
<h1>feeds</h1>
<div>
{this.props.channelsList.map(list =>
<li className="list-group-item list_pointer"
key={list.id}
onClick={()=>browserHistory.push('/feeds/channel/' + list.id)}>
{list.name}
</li>)
}
</div>
<div>
<AddForm
addNewChannel={(val) => {
this.props.addChannel(val)
}
}
/>
</div>
</div>
<div className="col-md-8 space_top">
{this.props.children && React.cloneElement(this.props.children, {
onDeleteChannel: this.props.deleteChannel,
channelsCount: this.props.channelsCount
})}
</div>
</div>
)
}
}
Feeds.propTypes = {
addChannel: PropTypes.func.isRequired,
fetchChannels: PropTypes.func.isRequired,
deleteChannel: PropTypes.func.isRequired,
selectChannel: PropTypes.func.isRequired,
channelsList:PropTypes.array.isRequired,
channelsCount: PropTypes.number.isRequired
};
export default Feeds
<file_sep>/src/routes/feeds/modules/feeds.js
import axios from 'axios';
// ------------------------------------
// Constants
// ------------------------------------
export const CHANNEL_ADD = 'CHANNEL_ADD'
export const COUNT_ADD = 'COUNT_ADD'
export const CHANNEL_SET_NAME = 'COUNT_ADD'
export const CHANNELS_GET = 'CHANNELS_GET'
export const CHANNELS_FETCH = 'CHANNELS_FETCH'
export const CHANNEL_SELECT = 'CHANNEL_SELECT'
export const CHANNEL_FETCH = 'CHANNEL_FETCH'
// ------------------------------------
// Actions
// ------------------------------------
export function selectChannel(channel) {
return {
type: CHANNEL_SELECT,
payload: channel
}
}
export function fetchChannels(channels = 'defaaq') {
return (dispatch) => {
dispatch({
type: CHANNELS_FETCH,
payload: 'channels'
})
return axios.get('http://54.187.164.175:1338/channels')
.then(function(response) {
return response.data.data
})
.then(res => dispatch(getChannels(res)));
}
}
export function getChannels(channels) {
return {
type: CHANNELS_GET,
payload: channels
}
}
export function setChannelName(channelName) {
return {
type: CHANNEL_SET_NAME,
payload: channelName
}
}
export function addChannel(channel = {
id: '',
name: '',
type: "",
url: ""
}) {
return (dispatch) => {
let config = {
headers: {
'Content-Type': 'application/vnd.api+json'
}
};
let body = JSON.stringify({
data: {
attributes: {
'name': channel.name,
'url': channel.url
}
}
});
axios.post('http://54.187.164.175:1338/channels', body, config)
.then(res => dispatch(fetchChannels()));
}
}
export function deleteChannel(channel_id) {
return (dispatch) => {
let url = 'http://54.187.164.175:1338/channels' + '/' + channel_id
let config = {
headers: {
'Content-Type': 'application/vnd.api+json'
}
};
axios.delete(url, config)
.then(res => dispatch(fetchChannels()));
}
}
export function addCount(value) {
return {
type: COUNT_ADD,
payload: value
}
}
export const actions = {
addCount,
addChannel
}
// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
[CHANNEL_ADD]: (state, action) => {
return { ...state
};
},
[CHANNELS_GET]: (state, action) => {
let newMylist = []
let channelsAmount = action.payload.length
action.payload.forEach((val) => newMylist.push(val))
state = { ...state,
channelsList: newMylist,
channelsCount: channelsAmount
}
return state;
},
[CHANNELS_FETCH]: (state, action) => {
return { ...state
}
},
[CHANNEL_SELECT]: (state, action) => {
state = { ...state,
selectedChannel: action.payload
}
return state;
}
}
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
channelsCount: 0,
channelsList: [{
id: '',
name: '',
type: "channels",
url: ""
}]
}
export default function counterReducer(state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
<file_sep>/src/routes/feeds/containers/AllFeedsList.js
import { connect } from 'react-redux'
import { addChannel, fetchChannels, deleteChannel, selectChannel } from '../modules/feeds'
import Feeds from '../components/FeedsList'
const mapStateToProps = (state, ownProps) => ({
channelsList : state.feeds.channelsList,
channelsCount: state.feeds.channelsCount
})
const mapDispatchToProps = {
addChannel: (value)=> addChannel(value),
fetchChannels: ()=> fetchChannels(),
deleteChannel: (id)=> deleteChannel(id),
selectChannel: (channel)=>selectChannel(channel)
}
const AllFeedsList = connect(
mapStateToProps,
mapDispatchToProps
)(Feeds)
export default AllFeedsList
<file_sep>/README.md
# RSS parser
RSS parser deployment guide
## Features
* [react](https://github.com/facebook/react)
* [redux](https://github.com/rackt/redux)
* [react-router](https://github.com/rackt/react-router)
* [webpack](https://github.com/webpack/webpack)
* [express](https://github.com/expressjs/express)
## Requirements
* node `^4.5.0`
* npm `^3.0.0`
### Installation
$ git clone <this-repository-url> <project-name>
$ cd <project-name>
$ npm install # Install project dependencies
## Running
$ npm start # Compile and launch
## Deployment
This project is deployable by serving the `~/dist` folder generated by `npm run deploy`. If you are serving the application via a web server such as nginx, make sure to direct incoming routes to the root `~/dist/index.html`
<file_sep>/src/routes/feeds/components/form.js
import React from 'react'
import { connect } from 'react-redux'
let AddForm = ({addNewChannel,bar, dispatch}) => {
let input
let inputurl
return (
<div className="space_top ">
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()||!inputurl.value.trim()) {
return
}
addNewChannel({url: inputurl.value, name : input.value})
input.value = ''
inputurl.value = ''
}}>
<div className="form-group" >
<label htmlFor="name" >Name</label>
<input className="form-control" id="name" ref={node => {
input = node
}} />
</div>
<div className="form-group " >
<label htmlFor="url">Url</label>
<input className="form-control" id="url" ref={node => {
inputurl = node
}} />
</div>
<div className="form-group" >
<button type="submit" className="btn btn-default">
Add Channel
</button>
</div>
</form>
</div>
)
}
AddForm = connect()(AddForm)
export default AddForm
<file_sep>/src/routes/channel/modules/channel.js
import axios from 'axios';
// ------------------------------------
// Constants
// ------------------------------------
export const CHANNEL_FETCH = 'CHANNEL_FETCH'
export const CHANNEL_GET_NEWS = 'CHANNEL_GET_NEWS'
export const CHANNEL_PARSE_FAIL = 'CHANNEL_PARSE_FAIL'
export const CHANNEL_GET = 'CHANNEL_GET'
export const CLEAN_SELECTED_CHANNEL = 'CLEAN_SELECTED_CHANNEL'
export const NEWS_SELECT = 'NEWS_SELECT'
export const NEWS_CHART_DATA_GET = 'NEWS_CHART_DATA_GET'
// ------------------------------------
// Actions
// ------------------------------------
export function fetchChannel(channel_id = '') {
return (dispatch) => {
return axios.get('http://54.187.164.175:1338/channels/' + channel_id)
.then(function(response) {
return response.data.data
})
.then(res => {
dispatch(channelGet(res))
return res
})
}
}
export function fetchChannelNews(channel_url = '') {
return (dispatch) => {
let query = 'select * from rss(0, 100) where url = "' + channel_url + '"';
let geturl = 'http://query.yahooapis.com/v1/public/yql?format=json&q=' + encodeURIComponent(query);
axios.get(geturl)
.then(function(response) {
return response.data.query.results.item
})
.then(res => dispatch(addNews(res)))
.catch(function(error) {
dispatch(channelParceFail())
})
}
}
export function channelParceFail() {
return {
type: CHANNEL_PARSE_FAIL
}
}
export function addNews(value) {
return {
type: CHANNEL_GET_NEWS,
payload: value
}
}
export function channelGet(value) {
return {
type: CHANNEL_GET,
payload: value
}
}
export function selectNews(value) {
return (dispatch) => {
dispatch({
type: NEWS_SELECT,
payload: value
})
dispatch(renewChartData(getLettersRate(value.description)))
}
}
export function cleanSelectedData(value) {
return {
type: CLEAN_SELECTED_CHANNEL,
payload: value
}
}
export function renewChartData(value) {
return {
type: NEWS_CHART_DATA_GET,
payload: value
}
}
function getLettersRate(strToParse) {
var div1 = document.createElement("div");
div1.innerHTML = strToParse;
var str = div1.textContent || div1.innerText || "";
function compareNumbers(a, b) {
return a - b;
}
var sums = [];
var otherSymbols = 0;
var lettersRate = {};
var str = str.toLowerCase();
str.split('').map(function(e) {
if (/[a-z]+/.test(e)) {
lettersRate[e] = !lettersRate[e] ? 1 : lettersRate[e] + 1;
} else otherSymbols++;
});
//if (otherSymbols) {lettersRate['other symbols'] = otherSymbols};
return lettersRate;
}
function getNewsAmount(str) {
return str.length
}
export const actions = {
fetchChannel
}
// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
[CHANNEL_FETCH]: (state, action) => {
return { ...state
}
},
[CHANNEL_GET_NEWS]: (state, action) => {
let news = []
let newsCount = getNewsAmount(action.payload)
action.payload.forEach((val) => news.push(val))
state = { ...state,
newsList: news,
newsAmount: newsCount,
parceChannelFail: false
}
return state
},
[CHANNEL_GET]: (state, action) => {
state = { ...state,
selectedChannel: action.payload
}
return state;
},
[NEWS_SELECT]: (state, action) => {
state = { ...state,
selectedNews: action.payload
}
return state;
},
[CLEAN_SELECTED_CHANNEL]: (state, action) => {
return { ...initialState
}
},
[NEWS_CHART_DATA_GET]: (state, action) => {
let letters = action.payload
let newLetterData = [];
function compareNumbers(a, b) {
return b.value - a.value;
}
for (var letter in letters) {
newLetterData.push({
label: letter,
value: letters[letter]
});
}
newLetterData.sort(compareNumbers);
state = { ...state,
pieChartData: newLetterData
}
return state;
},
[CHANNEL_PARSE_FAIL]: (state, action) => {
let chan = { ...state.selectedChannel
}
return { ...initialState,
selectedChannel: chan,
parceChannelFail: true
}
}
}
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
parceChannelFail: false,
newsAmount: 0,
pieChartData: [],
selectedNews: {
title: '',
attributes: {
url: ''
}
},
selectedChannel: {
attributes: {
name: ''
}
},
newsList: [{
title: '',
description: '',
link: ''
}]
}
export default function channelReducer(state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
|
7d87dca88bdbeb29533588b821844121c351c840
|
[
"JavaScript",
"Markdown"
] | 9
|
JavaScript
|
helmelix/rss_react_redux
|
295c4cd0063a61555326a5d574b8191e2e6f7fd1
|
e1779a1e546393df516b2d450710a2818b812c18
|
refs/heads/master
|
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.2.11
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: May 06, 2015 at 03:06
-- Server version: 5.6.21
-- PHP Version: 5.6.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `belanjaharian`
--
-- --------------------------------------------------------
--
-- Table structure for table `customer`
--
CREATE TABLE IF NOT EXISTS `customer` (
`customer_id` int(11) NOT NULL,
`customer_name` varchar(100) NOT NULL,
`customer_address` varchar(500) NOT NULL,
`customer_hp` varchar(20) NOT NULL,
`customer_birthdate` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `product`
--
CREATE TABLE IF NOT EXISTS `product` (
`product_id` int(11) NOT NULL,
`product_name` varchar(100) NOT NULL,
`product_brand` varchar(50) NOT NULL,
`product_image` varchar(150) NOT NULL,
`product_type_id` int(10) NOT NULL,
`product_size1` varchar(50) NOT NULL,
`product_price1` int(10) NOT NULL,
`product_size2` varchar(50) DEFAULT NULL,
`product_price2` int(10) DEFAULT NULL,
`product_size3` varchar(50) DEFAULT NULL,
`product_price3` int(10) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `product`
--
INSERT INTO `product` (`product_id`, `product_name`, `product_brand`, `product_image`, `product_type_id`, `product_size1`, `product_price1`, `product_size2`, `product_price2`, `product_size3`, `product_price3`) VALUES
(1, 'Apple Fuji', 'Fresho', 'Fresho - Apple Fuji', 1, '1 kg', 38000, '500 gr', 23000, NULL, NULL),
(2, 'Banana - Yelakki Semi Ripe (Grade A)', 'Fresho', 'Fresho - Banana - Yelakki Semi Ripe (Grade A)', 1, '1 kg', 10000, NULL, NULL, NULL, NULL),
(3, 'Beans - French Ring (Grade A)', 'Fresho', 'Fresho - Beans - French Ring (Grade A)', 2, '1 kg', 6000, NULL, NULL, NULL, NULL),
(4, 'Cabbage Small - Grade A', 'Fresho', 'Fresho - Cabbage Small - Grade A', 2, '1 pc', 5000, NULL, NULL, NULL, NULL),
(5, 'Capsicum Hybrid Green - Grade A', 'Fresho', 'Fresho - Capsicum Hybrid Green - Grade A', 2, '1 kg', 6000, NULL, NULL, NULL, NULL),
(6, 'Carrot Local - Grade A', 'Fresho', 'Fresho - Carrot Local - Grade A', 2, '1 kg', 7500, NULL, NULL, NULL, NULL),
(7, 'Cauliflower(medium) - Grade A', 'Fresho', 'Fresho - Cauliflower(medium) - Grade A', 2, '1 pc approx. 450 to 600 gr', 3500, NULL, NULL, NULL, NULL),
(8, 'Chilly Green Big - Grade A', 'Fresho', 'Fresho - Chilly Green Big - Grade A', 2, '250 gr', 2600, NULL, NULL, NULL, NULL),
(9, 'Coriander Hybrid - Grade A', 'Fresho', 'Fresho - Coriander Hybrid - Grade A', 2, '250 gr', 3500, NULL, NULL, NULL, NULL),
(10, 'Cucumber Hybrid - Grade A', 'Fresho', 'Fresho - Cucumber Hybrid - Grade A', 2, '1 kg', 2000, NULL, NULL, NULL, NULL),
(11, 'Fresh Ginger - Grade A', 'Fresho', 'Fresho - Fresh Ginger - Grade A', 2, '250 gr', 5000, NULL, NULL, NULL, NULL),
(12, 'Ladies Finger - Grade A', 'Fresho', 'Fresho - Ladies Finger - Grade A', 2, '1 kg', 8000, NULL, NULL, NULL, NULL),
(13, 'Lemon - Grade A', 'Fresho', 'Fresho - Lemon - Grade A', 1, '500 gr', 8000, NULL, NULL, NULL, NULL),
(14, 'Onion - Medium', 'Fresho', 'Fresho - Onion - Medium', 2, '1 kg', 5000, NULL, NULL, NULL, NULL),
(15, 'Papaya Local (Medium) - Grade A', 'Fresho', 'Fresho - Papaya Local (Medium) - Grade A', 1, '1 pc approx. 900 gr to 1 kg', 5000, NULL, NULL, NULL, NULL),
(16, 'Pomegranate - Kesar', 'Fresho', 'Fresho - Pomegranate - Kesar', 1, '1 kg', 30000, NULL, NULL, NULL, NULL),
(17, 'Potato', 'Fresho', 'Fresho - Potato', 2, '1 kg', 6000, NULL, NULL, NULL, NULL),
(18, 'Spinach', 'Fresho', 'Fresho - Spinach', 2, '500 gr', 5000, NULL, NULL, NULL, NULL),
(19, 'Tomato Hybrid - Grade A', 'Fresho', 'Fresho - Tomato Hybrid - Grade A', 1, '1 kg', 3200, NULL, NULL, NULL, NULL),
(20, 'Tomato Local - Grade A', 'Fresho', 'Fresho - Tomato Local - Grade A', 1, '1 kg', 2600, NULL, NULL, NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `product_type`
--
CREATE TABLE IF NOT EXISTS `product_type` (
`id_product_type` int(10) NOT NULL,
`product_type_name` varchar(30) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `product_type`
--
INSERT INTO `product_type` (`id_product_type`, `product_type_name`) VALUES
(1, 'buah'),
(2, 'sayur-umbi'),
(3, 'daging'),
(4, 'telur'),
(5, 'makanan'),
(6, 'minuman'),
(7, 'bacaan');
-- --------------------------------------------------------
--
-- Table structure for table `recipe`
--
CREATE TABLE IF NOT EXISTS `recipe` (
`recipe_id` int(11) NOT NULL,
`recipe_name` varchar(100) NOT NULL,
`recipe_image` varchar(150) NOT NULL,
`recipe_description` text NOT NULL,
`recipe_howto` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `recipe_composition`
--
CREATE TABLE IF NOT EXISTS `recipe_composition` (
`composition_id` int(11) NOT NULL,
`recipe_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`product_amount` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `supplier`
--
CREATE TABLE IF NOT EXISTS `supplier` (
`supplier_id` int(11) NOT NULL,
`supplier_name` varchar(100) NOT NULL,
`supplier_address` varchar(200) NOT NULL,
`supplier_hp` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `customer`
--
ALTER TABLE `customer`
ADD PRIMARY KEY (`customer_id`);
--
-- Indexes for table `product`
--
ALTER TABLE `product`
ADD PRIMARY KEY (`product_id`), ADD KEY `product_type_id` (`product_type_id`);
--
-- Indexes for table `product_type`
--
ALTER TABLE `product_type`
ADD PRIMARY KEY (`id_product_type`);
--
-- Indexes for table `recipe`
--
ALTER TABLE `recipe`
ADD PRIMARY KEY (`recipe_id`);
--
-- Indexes for table `recipe_composition`
--
ALTER TABLE `recipe_composition`
ADD PRIMARY KEY (`composition_id`);
--
-- Indexes for table `supplier`
--
ALTER TABLE `supplier`
ADD PRIMARY KEY (`supplier_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `customer`
--
ALTER TABLE `customer`
MODIFY `customer_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=21;
--
-- AUTO_INCREMENT for table `product_type`
--
ALTER TABLE `product_type`
MODIFY `id_product_type` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `recipe`
--
ALTER TABLE `recipe`
MODIFY `recipe_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `recipe_composition`
--
ALTER TABLE `recipe_composition`
MODIFY `composition_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `supplier`
--
ALTER TABLE `supplier`
MODIFY `supplier_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `product`
--
ALTER TABLE `product`
ADD CONSTRAINT `product_ibfk_1` FOREIGN KEY (`product_type_id`) REFERENCES `product_type` (`id_product_type`);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
d8597e8bcd91cd257b49244d59d40db743bca799
|
[
"SQL"
] | 1
|
SQL
|
nicolasruslim/TA_document
|
775b346438d6700dc611f99a38d3b962821df952
|
6361ebf64478c44db2a037c70f67259902003c9f
|
refs/heads/master
|
<file_sep>var dodger = document.getElementById("dodger");
function moveDodgerRight() {
var leftNumber = dodger.style.left.replace("px", "");
var left = parseInt(leftNumber, 10);
if (left < 360) {
dodger.style.left = `${left + 1}px`;
}
}
document.addEventListener("keydown", e => {if (e.which === 39) {
moveDodgerRight()
}
})
|
70f1897f7b432c8d170b7e1b372a568badbf522d
|
[
"JavaScript"
] | 1
|
JavaScript
|
ktbliz/js-eventing-acting-on-events-lab-dc-fe-skills-111218
|
d95831b6f112611650843ca53d26f4aabd84b6d1
|
dc0be41a23def807bfeeb37de198c4e4b7d24aad
|
refs/heads/master
|
<file_sep>function quickSort(array) {
if (array.length === 1) {
return array
}
const pivot = array[array.length - 1]
const leftArr = []
const rightArr =[]
for (let i = 0; i < array.length-1; i++){
if (array[i] < pivot) {
leftArr.push(array[i])
} else {
rightArr.push(array[i])
}
}
if (leftArr.length > 0 && rightArr.length > 0) {
return [...quickSort(leftArr), pivot, ...quickSort(rightArr)]
} else if (leftArr.length > 0) {
[...quickSort(leftArr), pivot]
} else {
[ pivot, ...quickSort(rightArr)]
}
return array
}
const array = [89, 30, 25, 32, 72, 70, 51, 42, 25, 24, 53, 55, 78, 50, 13, 40, 48, 32, 26, 2, 14, 33, 45, 72, 56, 44, 21, 88, 27, 68, 15, 62, 93, 98, 73, 28, 16, 46, 87, 28, 65, 38, 67, 16, 85, 63, 23, 69, 64, 91, 9, 70, 81, 27, 97, 82, 6, 88, 3, 7, 46, 13, 11, 64, 76, 31, 26, 38, 28, 13, 17, 69, 90, 1, 6, 7, 64, 43, 9, 73, 80, 98, 46, 27, 22, 87, 49, 83, 6, 39, 42, 51, 54, 84, 34, 53, 78, 40, 14, 5]
console.log(quickSort(array))
const data = '89 30 25 32 72 70 51 42 25 24 53 55 78 50 13 40 48 32 26 2 14 33 45 72 56 44 21 88 27 68 15 62 93 98 73 28 16 46 87 28 65 38 67 16 85 63 23 69 64 91 9 70 81 27 97 82 6 88 3 7 46 13 11 64 76 31 26 38 28 13 17 69 90 1 6 7 64 43 9 73 80 98 46 27 22 87 49 83 6 39 42 51 54 84 34 53 78 40 14 5';
const dataset = data.split(' ').map(num => Number(num));
<file_sep>const { merge } = require('./merge')
function sortBooks(array) {
if (array.length <= 1) {
return array
}
const middle = Math.floor(array.length / 2)
let left = array.slice(0, middle)
let right = array.slice(middle, array.length)
left = sortBooks(left)
right = sortBooks(right)
return merge(left, right,array)
}
const books = [
'Freakonomics',
'Medical Medium',
'Introvert Power',
'Drinking Closer To Home',
'The Good Girl',
'Gone Girl',
'Hollow City',
'Amelia',
'Water For Elephants',
'Hold Still'
];
console.log(sortBooks(books))<file_sep>function shuffleData(array, counter = 0) {
while (counter < array.length) {
let randomIndex = Math.floor(Math.random() * array.length)
let j = randomIndex
for (let i = 0; i < array.length; i++){
for (j = 0; j < array.length; j++){
[array[j], array[j + 1]] = [array[j + 1], array[j]]
counter++
return shuffleData(array,counter)
}
}
}
return array
}
console.log(shuffleData([1,2,3,4,5]))
|
dcd9ab6f42fea274ef75889abef46371e515d5c3
|
[
"JavaScript"
] | 3
|
JavaScript
|
SultanaK/DSA-Sorting
|
95b92fbade5d1a454e4131ca5fe443d5c1c7c817
|
686f77591c083cddb8db35ca5c878a791112a4da
|
refs/heads/master
|
<repo_name>seriojakarelin/news-explorer-frontend<file_sep>/src/components/PopupRegister/PopupRegister.js
import React from 'react';
import PopupWithForm from "../PopupWithForm/PopupWithForm";
import * as Auth from '../Auth/Auth';
function PopupRegister(props) {
const [email, setEmail] = React.useState('');
const [password, setPassword] = React.useState('');
const [userName, setUserName] = React.useState('');
function handleEmailChange(e) {
setEmail(e.target.value);
}
function handlePasswordChange(e) {
setPassword(e.target.value);
}
function handleUserNameChange(e) {
setUserName(e.target.value);
}
function handleSubmit(e){
e.preventDefault()
Auth.register(userName, email, password).then((res) => {
if (res) {
props.handleIsSignedUp();
props.handlePopupInfoOpen();
}
})
}
return (
<PopupWithForm
onClose={props.onClose}
isOpen={props.isOpen}
name={props.name}
title={props.title}
closingPopupsByOverlay={props.closingPopupsByOverlay}
>
<>
<label className="popup__label">
<p className="popup__input-name">Email</p>
<input className="popup__input" type="email" value={email} onChange={handleEmailChange} placeholder="Введите почту" required minLength="2" maxLength="30" />
<span className="popup__error">Неправильно введён email</span>
</label>
<label className="popup__label">
<p className="popup__input-name">Пароль</p>
<input className="popup__input" type="password" value={password} onChange={handlePasswordChange} placeholder="Введите пароль" required minLength="2" maxLength="30" />
<span className="popup__error">Неправильно введён пароля</span>
</label>
<label className="popup__label">
<p className="popup__input-name">Имя</p>
<input className="popup__input" type="text" value={userName} onChange={handleUserNameChange} placeholder="Введите имя" required minLength="2" maxLength="30" />
<span className="popup__error">Неправильно введено имя</span>
</label>
<button className="popup__button popup__button_type_login popup__button_blocked" onClick={handleSubmit}>Зарегистрироваться</button>
<p className="popup__text">или <span className="popup__link" onClick={props.changeRegisterToLogin}>Войти</span></p>
</>
</PopupWithForm>
);
}
export default PopupRegister;<file_sep>/src/components/SearchForm/SearchForm.js
import React from 'react';
function SearchForm() {
return (
<form className="search-form">
<h1 className="search-form__title">Что творится в мире?</h1>
<p className="search-form__text">Находите самые свежие статьи на любую тему и сохраняйте в своём личном кабинете</p>
<div className="search-form__search-line">
<input className="search-form__input" placeholder="Введите тему новости" type="text"></input>
<button className="search-form__submit-button" type="button">Искать</button>
</div>
</form>
);
}
export default SearchForm;<file_sep>/README.md
# news-explorer-api
Репозиторий для приложения проекта `News Explorer`, пока включающий только фронтенд.
Стек технологий: JavaScript, Git, HTML, CSS, React.<file_sep>/src/components/PopupInfo/PopupInfo.js
import React from 'react';
function PopupInfo(props) {
function onEnterClick() {
props.handlePopupLoginOpen();
}
return (
<section className={props.isOpen ? 'popup popup_type_info popup_opened' : 'popup popup_type_info'} onClick={props.closingPopupsByOverlay}>
<div className='popup__container popup__container_type_info'>
<h2 className="popup__title popup__title_type_info">Пользователь успешно зарегистрирован!</h2>
<div onClick={props.onClose} className="popup__close-button"></div>
<span onClick={props.onClose} className="popup__link" onClick={onEnterClick}>Войти</span>
</div>
</section>
)
}
export default PopupInfo;<file_sep>/src/components/SavedNewsInfo/SavedNewsInfo.js
import React from 'react';
function SavedNewsInfo() {
return (
<section className="saved-news-info">
<h2 className="saved-news-info__title">Сохранённые новости</h2>
<p className="saved-news-info__article-info">Грета, у вас 5 сохранённых статей</p>
<p className="saved-news-info__key-words">По ключевым словам: <span className="saved-news-info__key-words_font_bold">Природа, Тайга и 2-м другим</span></p>
</section>
);
}
export default SavedNewsInfo;<file_sep>/src/components/NewsCardList/NewsCardList.js
import React from 'react';
import { useLocation } from "react-router-dom";
import NewsCard from '../NewsCard/NewsCard';
function NewsCardList(props) {
const location = useLocation();
return (
<section className={props.isCardListShown ? "news-card-list" : "news-card-list_disabled"}>
<h2 className="news-card-list__heading" style={{ display: `${location.pathname === '/saved-news' ? 'none' : ''}` }}>Результаты поиска</h2>
<ul class="news-card-list__list">
<NewsCard
loggedIn={props.loggedIn}
/>
<NewsCard
loggedIn={props.loggedIn}
/>
<NewsCard
loggedIn={props.loggedIn}
/>
<NewsCard
loggedIn={props.loggedIn}
/>
</ul>
<button className="news-card-list__plus-button" type="button" style={{ display: `${location.pathname === '/saved-news' ? 'none' : ''}` }}>Показать ещё</button>
</section>
);
}
export default NewsCardList;<file_sep>/src/components/About/About.js
import React from 'react';
import author from '../../images/author.png';
function About() {
return (
<section className="about">
<img className="about__avatar" src={author} alt="<NAME>" />
<div className="about__info-container">
<h2 className="about__heading">Об авторе</h2>
<p className="about__text">Это блок с описанием автора проекта. Здесь следует указать, как вас зовут, чем вы занимаетесь, какими технологиями разработки владеете.</p>
<p className="about__text">Также можно рассказать о процессе обучения в Практикуме, чему вы тут научились, и чем можете помочь потенциальным заказчикам.</p>
</div>
</section>
);
}
export default About;<file_sep>/src/components/NewsCard/NewsCard.js
import React from 'react';
import newspic from '../../images/newspic.png';
import { useLocation } from "react-router-dom";
function NewsCard(props) {
const location = useLocation();
const [saveButtonClicked, setSaveButtonClicked] = React.useState(false);
function handleIsSaveButtonClicked() {
setSaveButtonClicked(!saveButtonClicked);
}
return (
<li className="news-card">
{location.pathname === '/saved-news'
?
<button
type="button"
className="news-card__trash-button">
</button>
:
<button
type="button"
onClick={handleIsSaveButtonClicked}
className={props.loggedIn ? (saveButtonClicked ? "news-card__save-button_marked" : "news-card__save-button news-card__save-button_type_login") : "news-card__save-button"}>
</button>
}
<img className="news-card__picture" src={newspic} alt="фото статьи" />
<div className="news-card__caption">
<p className="news-card__date">2 августа, 2019</p>
<h2 className="news-card__title">Национальное достояние – парки</h2>
<p className="news-card__text">В 2016 году Америка отмечала важный юбилей: сто лет назад здесь начала складываться система национальных парков –
охраняемых территорий, где и сегодня каждый может приобщиться к природе.
</p>
<p className="news-card__source">Лента.ру</p>
</div>
</li>
);
}
export default NewsCard;<file_sep>/src/components/SavedNewsHeader/SavedNewsHeader.js
import React from 'react';
import Navigation from '../Navigation/Navigation';
function SavedNewsHeader(props) {
return (
<>
<header className="app-header app-header_theme_white">
<div className="app-header__logo app-header__logo_theme_white">News Explorer</div>
<Navigation
loggedIn={props.loggedIn}
menuIsOpened={props.menuIsOpened}
handlePopupRegisterOpen={props.handlePopupRegisterOpen}
/>
{props.menuIsOpened || props.isPopupOpened
?
<button type="button" className="app-header__button app-header__button_type_close-white" onClick={props.handleExitButton}></button>
:
<button type="button" className="app-header__button app-header__button_theme_white" onClick={props.handleMenuIsOpened}></button>
}
</header>
<div className={props.menuIsOpened ? "app-header__overlay" : "app-header__overlay_invisible"}></div>
</>
);
}
export default SavedNewsHeader;<file_sep>/src/components/MainPageHeader/MainPageHeader.js
import React from 'react';
import AppHeader from '../AppHeader/AppHeader';
import SearchForm from '../SearchForm/SearchForm';
import SavedNewsInfo from '../SavedNewsInfo/SavedNewsInfo';
import SavedNewsHeader from '../SavedNewsHeader/SavedNewsHeader';
import { Route, Switch } from 'react-router-dom';
function MainPageHeader(props) {
const [menuIsOpened, setMenuIsOpened] = React.useState(false);
const isPopupOpened = props.isPopupLoginOpen === true || props.isPopupRegisterOpen === true || props.isPopupInfoOpen === true;
function handleMenuIsOpened() {
setMenuIsOpened(!menuIsOpened);
}
function handleExitButton() {
setMenuIsOpened(false);
props.closeAllPopups();
}
return (
<section className="main-header">
<Switch>
<Route exact path='/'>
<AppHeader
loggedIn={props.loggedIn}
menuIsOpened={menuIsOpened}
isPopupOpened={isPopupOpened}
handleExitButton={handleExitButton}
handleMenuIsOpened={handleMenuIsOpened}
handlePopupRegisterOpen={props.handlePopupRegisterOpen}
/>
<SearchForm />
</Route>
<Route path='/saved-news'>
<SavedNewsHeader
loggedIn={props.loggedIn}
handleMenuIsOpened={handleMenuIsOpened}
menuIsOpened={menuIsOpened}
handleExitButton={handleExitButton}
isPopupOpened={isPopupOpened}
handlePopupRegisterOpen={props.handlePopupRegisterOpen}
/>
<SavedNewsInfo />
</Route>
</Switch>
</section>
);
}
export default MainPageHeader;<file_sep>/src/components/PopupLogin/PopupLogin.js
import React from 'react';
import PopupWithForm from "../PopupWithForm/PopupWithForm";
function PopupLogin(props) {
const [email, setEmail] = React.useState('');
const [password, setPassword] = React.useState('');
function handleEmailChange(e) {
setEmail(e.target.value);
}
function handlePasswordChange(e) {
setPassword(e.target.value);
}
return (
<PopupWithForm
onClose={props.onClose}
isOpen={ props.isOpen }
name={props.name}
title={props.title}
closingPopupsByOverlay={props.closingPopupsByOverlay}
>
<>
<label className="popup__label">
<p className="popup__input-name">Email</p>
<input className="popup__input" type="email" value={email} onChange={handleEmailChange} placeholder="Введите почту" required minLength="2" maxLength="30" />
<span className="popup__error">Неправильно введён email</span>
</label>
<label className="popup__label">
<p className="popup__input-name">Пароль</p>
<input className="popup__input" type="password" value={password} onChange={handlePasswordChange} placeholder="Введите пароль" required minLength="2" maxLength="30" />
<span className="popup__error">Неправильно введён пароля</span>
</label>
<button className="popup__button popup__button_type_login popup__button_blocked">Войти</button>
<p className="popup__text">или <span className="popup__link" onClick={props.changeLoginToRegister}>Зарегистрироваться</span></p>
</>
</PopupWithForm>
);
}
export default PopupLogin;<file_sep>/src/components/Main/Main.js
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import About from '../About/About';
import NewsCardList from '../NewsCardList/NewsCardList';
import Preloader from '../Preloader/Preloader';
import NotFound from '../NotFound/NotFound';
function Main(props) {
return (
<section className="main">
<NewsCardList
loggedIn={props.loggedIn}
isCardListShown={props.isCardListShown}
/>
<Preloader
isPreloaderShown={props.isPreloaderShown}
/>
<NotFound
isNotFoundShown={props.isNotFoundShown}
/>
<Switch>
<Route exact path="/">
<About />
</Route>
</Switch>
</section>
);
}
export default Main;<file_sep>/src/components/PopupWithForm/PopupWithForm.js
import React from 'react'
function PopupWithForm(props) {
return (
<section className={props.isOpen ? `popup popup_type_${props.name} popup_opened` : `popup popup_type_${props.name}`} onClick={props.closingPopupsByOverlay}>
<div className={`popup__container popup__container_type_${props.name}`}>
<h2 className="popup__title"> {props.title} </h2>
<div onClick={props.onClose} className="popup__close-button"></div>
<form onSubmit={props.onSubmit} name={`${props.name}`} className="popup__form" noValidate>
{props.children}
</form>
</div>
</section>
)
}
export default PopupWithForm;
|
cc3c60e61d78b86448d3da9038276dacbe125b94
|
[
"JavaScript",
"Markdown"
] | 13
|
JavaScript
|
seriojakarelin/news-explorer-frontend
|
ea2de17894627d24ac474ee5042079e25a832782
|
5d0f47d1958b8ae51d0e6126e0f45a35e3954928
|
refs/heads/master
|
<file_sep>/*
** EPITECH PROJECT, 2021
** player2
** File description:
** player2
*/
#include "rpg.h"
void mv_win2(player_t *player, window_t *win, pbl_t * game)
{
if (sfKeyboard_isKeyPressed(sfKeyS) == sfTrue) {
if (collision_with_wall(game, win, 0, -player->speed) == 1)
return;
win->map_pos.y -= player->speed;
win->mvmnt.y -= player->speed;
}
if (sfKeyboard_isKeyPressed(sfKeyD) == sfTrue) {
if (collision_with_wall(game, win, -player->speed, 0) == 1)
return;
win->map_pos.x -= player->speed;
win->mvmnt.x -= player->speed;
}
}<file_sep>/*
** EPITECH PROJECT, 2021
** collisions with walls
** File description:
** collisions with walls
*/
#include "rpg.h"
int collision_with_wall(pbl_t *game, window_t *win, int dirx, int diry)
{
player_t *player = game->player;
int multx = dirx / player->speed == 0 ? 0 : dirx / player->speed;
int multy = diry / player->speed == 0 ? 0 : diry / player->speed;
int up = dirx == 0 && diry > 0 ? 40 : 0;
int right = dirx < 0 && diry == 0 ? 15 : 0;
int x = (-win->map_pos.x + player->object->pos.x + dirx +
67.25 + 50 * -multx - 12 - right) / 96;
int y = (-win->map_pos.y + player->object->pos.y + diry +
73 + 50 * -multy + 12 + up) / 96;
char obs = game->lvl->maps[game->lvl->lvl][y][x];
if (obs != ' ' && obs != '2')
return 0;
return 1;
}<file_sep>/*
** EPITECH PROJECT, 2020
** print_purcent
** File description:
** print_purcent
*/
#include "my_printf.h"
void print_mod_1(int i, char *str, va_list ap)
{
if (str[i + 1] == 'b')
print_binary(va_arg(ap, int));
if (str[i + 1] == 'c')
my_putchar_p(va_arg(ap, int));
if (str[i + 1] == 'i' || str[i + 1] == 'd')
my_put_nbr_p(va_arg(ap, int));
if (str[i + 1] == 's')
my_putstr_p(va_arg(ap, char *));
if (str[i + 1] == 'S')
my_putstr_octal_p(va_arg(ap, char *));
if (str[i + 1] == 'x')
print_hexa(va_arg(ap, int), 1);
if (str[i + 1] == 'X')
print_hexa(va_arg(ap, int), 2);
if (str[i + 1] == 'o')
print_octal_o(va_arg(ap, int));
if (str[i + 1] == 'u')
my_put_nbr_p(va_arg(ap, unsigned int));
if (str[i + 1] == '%')
my_putchar_p('%');
}
void print_mod_2(int i, char *str, va_list ap)
{
if (str[i + 1] == 'e')
print_mod_e(va_arg(ap, double));
if (str[i + 1] == 'E')
print_mod_cape(va_arg(ap, double));
if (str[i + 1] == 'f')
print_mod_f(va_arg(ap, double));
}
void print_mod(int i, char *str, va_list ap)
{
if (str[i + 1] == '-' || str[i + 1] == '+'
|| str[i + 1] == ' ' || str[i + 1] == '\''
|| str[i + 1] == '#')
va_arg(ap, void *);
print_mod_1(i, str, ap);
print_mod_2(i, str, ap);
}
<file_sep>/*
** EPITECH PROJECT, 2021
** draw_weapons
** File description:
** draw_weapons
*/
#include "rpg.h"
void draw_inv_weapons(inventory_t *inv, window_t *win)
{
for (int i = 0; i < 22; ++i)
if (inv->items[i] != NULL) {
inv->items[i]->object = init_pos(inv->items[i]->object,
inv->slot_pos[i][0], inv->slot_pos[i][1]);
draw(win->window, inv->items[i]->object->sprite);
}
}
void draw_hot_weapons(inventory_t *inv, window_t *win)
{
draw(win->window, inv->hotbar->sprite);
for (int i = 21; i < 24; ++i)
if (inv->items[i] != NULL) {
inv->items[i]->object = init_pos(
inv->items[i]->object, inv->slot_pos[i][0], inv->slot_pos[i][1]);
draw(win->window, inv->items[i]->object->sprite);
}
}
<file_sep>/*
** EPITECH PROJECT, 2021
** player
** File description:
** player
*/
#include "rpg.h"
void player_animation(object_t *object, int mv, int lim, float ms)
{
sfTime time = sfClock_getElapsedTime(object->clock);
if ((time.microseconds / (ms * 1000.0)) > 1) {
object->rect.left += mv;
sfClock_restart(object->clock);
}
if (object->rect.left >= lim)
object->rect.left = 0;
}
player_t *get_direction(player_t *player, window_t *win)
{
if (win->mouse.x < 990 && win->mouse.y >= 360 && win->mouse.y <= 720)
player->direction = 1;
if (win->mouse.x > 990 && win->mouse.y >= 360 && win->mouse.y <= 720)
player->direction = 2;
if (win->mouse.y < 450 && win->mouse.x >= 640 && win->mouse.x <= 1280)
player->direction = 3;
if (win->mouse.y > 630 && win->mouse.x >= 640 && win->mouse.x <= 1280)
player->direction = 4;
return player;
}
player_t *get_run_stand(player_t *player)
{
if (player->direction == 1)
player->object->rect.top = 134;
if (player->direction == 2)
player->object->rect.top = 268;
if (player->direction == 3)
player->object->rect.top = 402;
if (player->direction == 4)
player->object->rect.top = 0;
if (player->direction == -1)
player->object->rect.left = 100;
if (player->direction == -2)
player->object->rect.left = 100;
if (player->direction == -3)
player->object->rect.left = 100;
if (player->direction == -4)
player->object->rect.left = 100;
return player;
}
void mv_win(player_t *player, window_t *win, pbl_t * game)
{
if (sfKeyboard_isKeyPressed(sfKeyZ) == sfTrue) {
if (collision_with_wall(game, win, 0, player->speed) == 1)
return;
win->map_pos.y += player->speed;
win->mvmnt.y += player->speed;
}
if (sfKeyboard_isKeyPressed(sfKeyQ) == sfTrue) {
if (collision_with_wall(game, win, player->speed, 0) == 1)
return;
win->map_pos.x += player->speed;
win->mvmnt.x += player->speed;
}
return mv_win2(player, win, game);
}
void animate_player(player_t *player, window_t *win, pbl_t * game)
{
if (win->quest->mod == 3)
player = get_direction(player, win);
player = get_run_stand(player);
sfSprite_setTextureRect(player->object->sprite, player->object->rect);
if (win->quest->mod == 3 && (sfKeyboard_isKeyPressed(sfKeyZ) == sfTrue
|| sfKeyboard_isKeyPressed(sfKeyQ) == sfTrue
|| sfKeyboard_isKeyPressed(sfKeyS) == sfTrue
|| sfKeyboard_isKeyPressed(sfKeyD) == sfTrue) && win->l_state == 0 ) {
player_animation(player->object, 100, player->lim, 100);
mv_win(player, win, game);
} else if (player->direction > 0) {
player->direction *= -1;
player = get_run_stand(player);
}
draw_chests(win, game->lvl, player);
player->stats = update_stats(win, player->stats);
display_xp_life(win, player);
player = heal(win, player->orb, player);
sfSprite_setPosition(player->object->sprite, player->object->pos);
draw(win->window, player->object->sprite);
}<file_sep>/*
** EPITECH PROJECT, 2021
** create_text
** File description:
** create_text
*/
#include "rpg.h"
text_t *create_text(char *str, int x, int y, int size)
{
text_t *text = malloc(sizeof(text_t));
text->text = sfText_create();
text->pos.x = x;
text->pos.y = y;
sfText_setString(text->text, str);
sfText_setFont(text->text, sfFont_createFromFile("image/stat_f.otf"));
sfText_setCharacterSize(text->text, size);
sfText_setColor(text->text, sfColor_fromRGB(200, 200, 200));
sfText_setPosition(text->text, text->pos);
return text;
}
text_t *create_text2(char *str, int x, int y, int size)
{
text_t *text = malloc(sizeof(text_t));
text->text = sfText_create();
text->pos.x = x;
text->pos.y = y;
sfText_setString(text->text, str);
sfText_setFont(text->text, sfFont_createFromFile("image/stat_f.otf"));
sfText_setCharacterSize(text->text, size);
sfText_setColor(text->text, sfColor_fromRGB(255, 255, 255));
sfText_setPosition(text->text, text->pos);
return text;
}<file_sep>/*
** EPITECH PROJECT, 2021
** transi
** File description:
** transi
*/
#include "rpg.h"
void transition(window_t *win)
{
if (win->t_state == 1)
win->transcolor += 5;
if (win->transcolor >= 255) {
win->mod = win->t_mod;
win->t_state = 2;
}
if (win->t_state == 2)
win->transcolor -= 10;
if (win->transcolor <= 0) {
win->transcolor = 0;
win->t_state = 0;
}
sfSprite_setColor(win->trans->sprite,
sfColor_fromRGBA(0, 0, 0, win->transcolor));
draw(win->window, win->trans->sprite);
}
void launch_transition(window_t *win, int mod)
{
win->t_mod = mod;
win->t_state = 1;
}<file_sep>/*
** EPITECH PROJECT, 2020
** mod_e
** File description:
** mod_e
*/
#include "../my_printf.h"
int *get_arr(int *arr, double nb, unsigned long long nbr)
{
if (nb < 0)
nb *= -1;
arr = malloc(sizeof(int) * 2);
arr[0] = 0;
arr[1] = 0;
if (nb > 1) {
for (int i = nb; i > 1; i /= 10, arr[0]++);
for (int i = nbr; i > 9; i /= 10, arr[1]++);
} else if (nb < 1 && nb > 0) {
for (double i = nb; i < 1; i *= 10, arr[0]++);
for (int i = nbr; i > 9; i /= 10, arr[1]++);
}
return arr;
}
int get_number(double n, unsigned long long nbr)
{
double nb = n;
if (nb < 0)
nb *= -1;
if (nb < 1 && nb > 0)
for (;nb < 1; nb *= 10);
nbr = nb * 1000000;
return nbr;
}
void print_mod_e(double nb)
{
unsigned long long nbr = get_number(nb, nbr);
int *arr = get_arr(arr, nb, nbr);
if (nb < 0) {
nb *= -1;
my_putchar_p('-');
}
my_put_nbr_p(nbr / my_pow(10, arr[1]));
my_putchar_p('.');
arr[1]--;
for (int i = 1; i <= 6; i++, arr[1]--) {
my_put_nbr_p((nbr / my_pow(10, arr[1])) % 10);
}
if (nb > 1)
my_putstr_p("e+");
else if (nb < 1 && nb > 0)
my_putstr_p("e-");
if (arr[0] < 10)
my_putchar_p('0');
my_put_nbr_p(arr[0]);
}
<file_sep>/*
** EPITECH PROJECT, 2021
** create_object.c
** File description:
** create_object
*/
#include "rpg.h"
object_t *create_object(char *pth, int x, int y)
{
object_t *object = malloc(sizeof(object_t));
object->texture = sfTexture_createFromFile(pth , NULL);
object->sprite = sfSprite_create();
sfSprite_setTexture(object->sprite, object->texture, 0);
object->pos.x = x;
object->pos.y = y;
sfSprite_setPosition(object->sprite, object->pos);
object->scale.x = 1;
object->scale.y = 1;
sfSprite_setScale(object->sprite, object->scale);
object->plus = 207;
object->open = 0;
object->is_closed = 0;
return object;
}
object_t *init_rect(object_t *object, int width, int height, int top)
{
object->rect.width = width;
object->rect.height = height;
object->rect.top = top;
object->rect.left = 0;
sfSprite_setTextureRect(object->sprite, object->rect);
return object;
}
object_t *init_pos(object_t *object, int x, int y)
{
object->pos.x = x;
object->pos.y = y;
sfSprite_setPosition(object->sprite, object->pos);
return object;
}
void animation(object_t *object, int mv, int lim, float ms)
{
sfTime time = sfClock_getElapsedTime(object->clock);
if ((time.microseconds / (ms * 1000.0)) > 1) {
object->rect.left += mv;
sfClock_restart(object->clock);
}
if (object->rect.left >= lim)
object->rect.left = 0;
sfSprite_setTextureRect(object->sprite, object->rect);
}
en_list *create_en_object(int lvl, en_list *list)
{
int random_int = rand() % 100;
if (random_int < 70) {
list->lvl = lvl;
list->speed = 5;
list->life = 80 + 5 * lvl;
list->dmg = 10 + 2 * lvl;
list->object = create_object("image/blueghost.png", 0, 0);
} else {
list->lvl = lvl;
list->speed = 3;
list->life = 110 + 10 * lvl;
list->dmg = 15 + 3 * lvl;
list->object = create_object("image/whiteghost.png", 0, 0);
}
list->object->clock = sfClock_create();
list->object = init_rect(list->object, 96, 96, 2);
list->can_attack = 1;
list->attack_clock = sfClock_create();
return list;
}<file_sep>/*
** EPITECH PROJECT, 2021
** quest
** File description:
** quest
*/
#include "rpg.h"
quest_t *create_quest(void)
{
quest_t *quest = malloc(sizeof(quest_t));
quest->chatbox = create_object("image/chatbox.png", 0, 0);
quest->eugena = create_object("image/eugena.png", 0, 0);
quest->hello = create_object("image/hello.png", 0, 0);
quest->abandon = create_object("image/abandon.png", 0, 0);
quest->touches = create_object("image/touches.png", 0, 0);
quest->goodluck = create_object("image/goodluck.png", 0, 0);
quest->presse = create_object("image/presse.png", 0, 0);
quest->pressenter = create_object("image/pressenter.png", 0, 0);
quest->chatbox = init_rect(quest->chatbox, 1920, 1080, 0);
quest->eugena = init_rect(quest->eugena, 1920, 1080, 0);
quest->hello = init_rect(quest->hello, 47, 1080, 0);
quest->abandon = init_rect(quest->abandon, 44, 1080, 0);
quest->touches = init_rect(quest->touches, 48, 1080, 0);
quest->goodluck = init_rect(quest->goodluck, 48, 1080, 0);
quest->presse = init_rect(quest->presse, 1383, 1080, 0);
quest->pressenter = init_rect(quest->pressenter, 1312, 1080, 0);
quest->mod = 0;
return quest;
}
void set_quest_rects(window_t *win, quest_t *quest)
{
sfSprite_setTextureRect(quest->hello->sprite, quest->hello->rect);
sfSprite_setTextureRect(quest->abandon->sprite, quest->abandon->rect);
sfSprite_setTextureRect(quest->touches->sprite, quest->touches->rect);
sfSprite_setTextureRect(quest->goodluck->sprite, quest->goodluck->rect);
sfSprite_setTextureRect(quest->presse->sprite, quest->presse->rect);
sfSprite_setTextureRect(quest->pressenter->sprite, quest->pressenter->rect);
}
void draw_questbox(window_t *win, quest_t *quest)
{
if (quest->mod >= 0 && quest->mod <= 2) {
set_quest_rects(win, quest);
draw(win->window, quest->chatbox->sprite);
draw(win->window, quest->eugena->sprite);
}
if (quest->mod == 1) {
draw(win->window, quest->hello->sprite);
draw(win->window, quest->abandon->sprite);
draw(win->window, quest->presse->sprite);
} else if (quest->mod == 2) {
draw(win->window, quest->touches->sprite);
draw(win->window, quest->goodluck->sprite);
draw(win->window, quest->pressenter->sprite);
}
}
void do_questmod2(window_t *win, quest_t *quest)
{
if (quest->mod >= 0 && quest->mod <= 2
&& sfKeyboard_isKeyPressed(sfKeyEnter) == sfTrue) {
sfSound_play(win->sound->list[5]);
quest->mod = 3;
}
if (quest->touches->rect.width <= 1093 && quest->mod == 2)
quest->touches->rect.width += 7;
if (quest->goodluck->rect.width <= 169
&& quest->touches->rect.width >= 1093)
quest->goodluck->rect.width += 7;
if (quest->pressenter->rect.width <= 1654
&& quest->goodluck->rect.width >= 169)
quest->pressenter->rect.width += 7;
if (quest->pressenter->rect.width >= 1654
&& sfKeyboard_isKeyPressed(sfKeyEnter) == sfTrue) {
sfSound_play(win->sound->list[5]);
quest->mod = 3;
}
draw_questbox(win, quest);
}
void draw_quest(window_t *win, quest_t *quest)
{
static int start = 0;
if (start < 101)
start += 2;
if (start == 100)
quest->mod = 1;
if (quest->hello->rect.width <= 698 && quest->mod == 1)
quest->hello->rect.width += 7;
if (quest->hello->rect.width >= 698
&& quest->abandon->rect.width <= 1157)
quest->abandon->rect.width += 7;
if (quest->abandon->rect.width >= 1157
&& quest->presse->rect.width <= 1637)
quest->presse->rect.width += 7;
if (quest->presse->rect.width >= 1637 && quest->mod == 1
&& sfKeyboard_isKeyPressed(sfKeyE) == sfTrue) {
sfSound_play(win->sound->list[5]);
quest->mod = 2;
}
do_questmod2(win, quest);
}<file_sep>/*
** EPITECH PROJECT, 2021
** main menu
** File description:
** main menu
*/
#include "rpg.h"
void move_utils(object_t *object, window_t *win, int y)
{
if (win->mouse.x >= 0 && win->mouse.y >= y && win->mouse.x <= 204
&& win->mouse.y <= y + 86) {
if (object->pos.x < 0)
object->pos.x += 15;
} else
if (object->pos.x > -90)
object->pos.x -= 15;
sfSprite_setPosition(object->sprite, object->pos);
}
int icon_hb(window_t *win, int y)
{
if (win->mouse.x >= 0 && win->mouse.y >= y && win->mouse.x <= 204
&& win->mouse.y <= y + 86
&& sfMouse_isButtonPressed(sfMouseLeft) == sfTrue) {
sfSound_play(win->sound->list[5]);
return 1;
}
return 0;
}
void do_menu_mod(object_l *menu, window_t *win)
{
if ((menu->mod == 1 || menu->mod == 2)
&& sfKeyboard_isKeyPressed(sfKeyEscape) == sfTrue)
menu->mod = 0;
if (menu->mod == 1)
my_info(menu, win);
if (menu->mod == 2) {
my_pause(menu, win);
controle_menu_sound(menu, win);
}
if (menu->mod == 3) {
draw(win->window, menu->sure->sprite);
if (win->mouse.x >= 1072 && win->mouse.y >= 500
&& win->mouse.x <= 1287 && win->mouse.y <= 663 &&
sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
sfRenderWindow_close(win->window);
else if (win->mouse.x >= 673 && win->mouse.y >= 488
&& win->mouse.x <= 854 && win->mouse.y <= 668 &&
sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
menu->mod = 0;
}
}
void main_menu_conditions(object_l *menu, window_t *win)
{
if (win->mouse.x >= 823 && win->mouse.y >= 803
&& win->mouse.x <= 1087 && win->mouse.y <= 890 && menu->mod == 0) {
draw(win->window, menu->bigstart->sprite);
if (sfMouse_isButtonPressed(sfMouseLeft) == sfTrue) {
sfSound_play(win->sound->list[5]);
launch_transition(win, 1);
}
} else
draw(win->window, menu->start->sprite);
if (icon_hb(win, 158) == 1) {
draw(win->window, menu->param->sprite);
menu->mod = 3;
}
if (icon_hb(win, 282) == 1)
menu->mod = 1;
if (icon_hb(win, 408) == 1)
menu->mod = 2;
do_menu_mod(menu, win);
}
void main_menu(object_l *menu, window_t *win)
{
draw(win->window, win->trans->sprite);
draw_main_menu(menu, win);
main_menu_conditions(menu, win);
menu->starback->pos.x -= 3;
if (menu->starback->pos.x <= -1920)
menu->starback->pos.x = 0;
sfSprite_setPosition(menu->starback->sprite, menu->starback->pos);
if (menu->mod == 0) {
move_utils(menu->exit, win, 158);
move_utils(menu->info, win, 282);
move_utils(menu->param, win, 408);
}
transition(win);
}<file_sep>/*
** EPITECH PROJECT, 2020
** B-MUL-200-PAR-2-1-myrpg-julien.de-waele
** File description:
** my_info.c
*/
#include "rpg.h"
void my_info(object_l *menu, window_t *win)
{
static int i = 0;
if (i == 0)
draw(win->window, menu->info_one->sprite);
if (win->mouse.x >= 1218 && win->mouse.y >= 800
&& win->mouse.x <= 1296 && win->mouse.y <= 823 &&
sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
i = 1;
if (i == 1)
draw(win->window, menu->info_two->sprite);
if (win->mouse.x >= 611 && win->mouse.y >= 787
&& win->mouse.x <= 723 && win->mouse.y <= 823 && i == 1 && i == 1 &&
sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
i = 0;
}<file_sep>/*
** EPITECH PROJECT, 2021
** mode
** File description:
** mode
*/
#include "rpg.h"
void game_loop(pbl_t *game, window_t *win)
{
my_fps(win);
draw_ground(win, game, game->lvl);
if (sfKeyboard_isKeyPressed(sfKeyO) == sfTrue
&& game->player->inv->display != 1 && win->mod == 1)
launch_transition(win, 3);
if (game->lvl->lvl != 0)
mv_ennemies(win, game->lvl->ennemy[game->lvl->lvl], game->player);
shoot(game->player, win);
animate_player(game->player, win, game);
inventory_display(game->player, win);
draw_minimap(win, game->lvl, game->player);
draw_quest(win, win->quest);
if (game->player->stats->life <= 0)
launch_transition(win, 2);
else
lvl_transition(win, game->lvl, game->player, game);
transition(win);
}
void pause_menu(pbl_t *game, window_t *win)
{
draw(win->window, win->setting->sprite);
controle_game_sound(game->menu, win);
if (win->mouse.x >= 680 && win->mouse.x <= 758
&& win->mouse.y >= 737 && win->mouse.y <= 783
&& sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
sfRenderWindow_close(win->window);
if (win->mouse.x >= 1188 && win->mouse.x <= 1247
&& win->mouse.y >= 737 && win->mouse.y <= 780
&& sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
launch_transition(win, 1);
transition(win);
}
void mode(pbl_t *game, window_t *win)
{
win->mouse = sfMouse_getPositionRenderWindow(win->window);
for (int i = 0; i < 12; i++)
sfSound_setVolume(win->sound->list[i], win->snd);
sfMusic_setVolume(win->sound->music, win->snd);
if (sfKeyboard_isKeyPressed(sfKeyP) == sfTrue)
sfRenderWindow_close(win->window);
if (win->mod == 0)
main_menu(game->menu, win);
if (win->mod == 1)
game_loop(game, win);
if (win->mod == 2)
do_lose(win, game->lose);
if (win->mod == 3)
pause_menu(game, win);
if (win->mod == 4) {
draw(win->window, win->win_screen->sprite);
if (sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
sfRenderWindow_close(win->window);
}
}<file_sep>/*
** EPITECH PROJECT, 2021
** create_window
** File description:
** create_window
*/
#include "rpg.h"
window_t *create_window2(window_t *win)
{
win->t_state = 0;
win->t_mod = 0;
win->l_state = 0;
win->l_mod = 0;
win->mvmnt.x = 0.0;
win->mvmnt.y = 0.0;
win->fps = 30;
sfRenderWindow_setFramerateLimit(win->window, 30);
win->quest = create_quest();
win->sound_m = create_object("image/bar1.png", 0, 0);
win->sound_g = create_object("image/bar2.png", 0, 0);
win->sound_m = init_rect(win->sound_m, 766, 1080, 0);
win->sound_g = init_rect(win->sound_g, 780, 1080, 0);
win->snd = 100;
win->setting = create_object("image/setting.png", 0, 0);
win->win_screen = create_object("image/win.png", 666, 327);
win->snd = 50.0;
return win;
}
window_t *create_window(void)
{
window_t *win = malloc(sizeof(window_t));
sfVideoMode mode = {1920, 1080, 32};
win->window = sfRenderWindow_create(mode, "SPACE RANGER", sfClose, NULL);
win->mod = 0;
win->trans = create_object("./image/transition.png", 0, 0);
win->back = create_object("./image/back.jpg", 0, 0);
win->trans->rect.width = 1920;
win->trans->rect.height = 1080;
win->transcolor = 0;
win->trans->rect.top = 0;
win->trans->rect.left = 0;
sfSprite_setTextureRect(win->trans->sprite, win->trans->rect);
win = create_window2(win);
win->sound = init_audio();
sfMusic_play(win->sound->music);
return win;
}<file_sep>/*
** EPITECH PROJECT, 2021
** shoot_2
** File description:
** shoot_2
*/
#include "rpg.h"
shoot_t *create_bullet(char *pth, player_t *player, int x, int y)
{
shoot_t *object = malloc(sizeof(shoot_t));
object->texture = sfTexture_createFromFile(pth , NULL);
object->sprite = sfSprite_create();
sfSprite_setTexture(object->sprite, object->texture, 0);
sfSprite_setPosition(object->sprite, object->pos);
player->shootpos = player->object->pos;
object->direction = player->shootdir;
object->dmg = player->weapon->dmg;
object->clock = sfClock_create();
object->pos.x = x;
object->pos.y = y;
player->object->scale.x += 0.03;
return object;
}
shoot_t *init_bullet_rect(shoot_t *object, int width, int height, int top)
{
object->rect.width = width;
object->rect.height = height;
object->rect.top = top;
object->rect.left = 0;
sfSprite_setTextureRect(object->sprite, object->rect);
return object;
}
player_t *destroy_bullet(player_t *player, int i)
{
if (player->shoot[i]->pos.x <= player->shootpos.x - 370
|| player->shoot[i]->pos.x >= player->shootpos.x + 450
|| player->shoot[i]->pos.y <= player->shootpos.y - 370
|| player->shoot[i]->pos.y >= player->shootpos.y + 485) {
player->shoot[i] = NULL;
}
return player;
}
void shake(player_t *player)
{
sfVector2f pos = player->object->pos;
static float mult_scale = 0.03;
if (player->object->scale.x != 1) {
player->object->scale.x += mult_scale;
player->object->scale.y = player->object->scale.x;
player->object->pos.x -= mult_scale * 50;
player->object->pos.y -= mult_scale * 60;
}
if (player->object->scale.x >= 1.1)
mult_scale *= -1;
if (player->object->scale.x == 1) {
player->object->pos.x = pos.x;
player->object->pos.y = pos.y;
mult_scale = 0.03;
}
sfSprite_setPosition(player->object->sprite, player->object->pos);
sfSprite_setScale(player->object->sprite, player->object->scale);
}
void animat_bullet(shoot_t *object, int mv, int lim, float ms)
{
sfTime time = sfClock_getElapsedTime(object->clock);
if ((time.microseconds / (ms * 1000.0)) > 1) {
object->rect.left += mv;
sfClock_restart(object->clock);
}
if (object->rect.left >= lim)
object->rect.left = 0;
sfSprite_setTextureRect(object->sprite, object->rect);
}<file_sep>/*
** EPITECH PROJECT, 2021
** init chests
** File description:
** init chests
*/
#include "rpg.h"
object_t **create_lvl_chests(level_t *lvl, int x_spawn, int y_spawn, int level)
{
object_t **chests = NULL;
int nb = 0;
for (int i = 1; lvl->maps[level][i] != NULL; i++)
for (int t = 0; lvl->maps[level][i][t] != '\0'; t++)
if (lvl->maps[level][i][t] == '2')
++nb;
chests = malloc(sizeof(object_t) * nb);
nb = 0;
for (int i = 1; lvl->maps[level][i] != NULL; i++)
for (int t = 0; lvl->maps[level][i][t] != '\0'; t++)
if (lvl->maps[level][i][t] == '2') {
chests[nb] = create_object("image/chest.png",
t * 96 + x_spawn - 55, i * 96 + y_spawn - 20);
chests[nb]->clock = sfClock_create();
chests[nb] = init_rect(chests[nb], 207, 130, 0);
++nb;
}
chests[nb] = NULL;
return chests;
}
object_t ***create_all_chests(level_t *lvl)
{
object_t ***chests = malloc(sizeof(object_t **) * 11);
for (int i = 0; i < 11; i++)
chests[i] = create_lvl_chests(lvl,
lvl->spawns[i].x, lvl->spawns[i].y, i);
return chests;
}
void anim_chest1(object_t *object)
{
sfTime time = sfClock_getElapsedTime(object->clock);
if ((time.microseconds / (200000.0)) > 1) {
object->rect.left += object->plus;
sfClock_restart(object->clock);
if (object->rect.left >= 414 || object->rect.left <= 0)
object->plus = object->plus * -1;
}
sfSprite_setTextureRect(object->sprite, object->rect);
}
void anim_chest2(object_t *object)
{
sfTime time = sfClock_getElapsedTime(object->clock);
if ((time.microseconds / (200000.0)) > 1) {
if (object->open == 1)
object->rect.left += object->plus;
sfClock_restart(object->clock);
if (object->open == 0)
object->rect.left += 207;
if (object->rect.left > 1035)
object->open = 1;
if ((object->rect.left >= 2069 || object->rect.left <= 1035)
&& object->open == 1)
object->plus = object->plus * -1;
}
sfSprite_setTextureRect(object->sprite, object->rect);
}
void draw_chests(window_t *win, level_t *lvl, player_t *player)
{
for (int i = 0; lvl->chests[lvl->lvl][i] != NULL && lvl->lvl != 0; i++) {
if (lvl->chests[lvl->lvl][i]->is_closed == 1)
anim_chest2(lvl->chests[lvl->lvl][i]);
if (lvl->chests[lvl->lvl][i]->is_closed == 0)
anim_chest1(lvl->chests[lvl->lvl][i]);
draw(win->window, lvl->chests[lvl->lvl][i]->sprite);
if (open_chest(win, lvl, player, i) == 1
&& lvl->chests[lvl->lvl][i]->is_closed == 0) {
lvl->chests[lvl->lvl][i]->is_closed = 1;
sfSound_play(win->sound->list[8]);
player->inv = generate_weapon(player->inv);
}
lvl->chests[lvl->lvl][i]->pos.x += win->mvmnt.x;
lvl->chests[lvl->lvl][i]->pos.y += win->mvmnt.y;
sfSprite_setPosition(lvl->chests[lvl->lvl][i]->sprite,
lvl->chests[lvl->lvl][i]->pos);
}
}<file_sep>/*
** EPITECH PROJECT, 2021
** weapon_stats
** File description:
** weapon_stats
*/
#include "rpg.h"
void put_weapon_info(weapon_t *item, inventory_t *inv, window_t *win, int x)
{
inv->stat_txt->pos.x = 1470 + x;
inv->stat_txt->pos.y = 390;
sfText_setString(inv->stat_txt->text, my_itoa(item->dmg));
sfText_setPosition(inv->stat_txt->text, inv->stat_txt->pos);
sfRenderWindow_drawText(win->window, inv->stat_txt->text, NULL);
inv->stat_txt->pos.x = 1470 + x;
inv->stat_txt->pos.y = 460;
sfText_setString(inv->stat_txt->text, my_itoa(item->ms / 100));
sfText_setPosition(inv->stat_txt->text, inv->stat_txt->pos);
sfRenderWindow_drawText(win->window, inv->stat_txt->text, NULL);
}
void put_diff2(int nb, int y, inventory_t *inv, window_t *win)
{
inv->stat_txt->pos.x = 1610;
inv->stat_txt->pos.y = 390 + y;
sfText_setString(inv->stat_txt->text, my_itoa(nb));
sfText_setPosition(inv->stat_txt->text, inv->stat_txt->pos);
sfRenderWindow_drawText(win->window, inv->stat_txt->text, NULL);
}
void put_diff(inventory_t *inv, window_t *win)
{
int dmg = inv->stock->dmg - inv->items[inv->s_index]->dmg;
int ms = (inv->stock->ms - inv->items[inv->s_index]->ms) / 100;
if (dmg > 0)
sfText_setColor(inv->stat_txt->text, sfColor_fromRGB(60, 179, 113));
else if (dmg < 0)
sfText_setColor(inv->stat_txt->text, sfColor_fromRGB(139, 0, 0));
else
sfText_setColor(inv->stat_txt->text, sfColor_fromRGBA(0, 0, 0, 0));
put_diff2(dmg, 0, inv, win);
if (ms > 0)
sfText_setColor(inv->stat_txt->text, sfColor_fromRGB(139, 0, 0));
else if (ms < 0)
sfText_setColor(inv->stat_txt->text, sfColor_fromRGB(60, 179, 113));
else
sfText_setColor(inv->stat_txt->text, sfColor_fromRGBA(0, 0, 0, 0));
put_diff2(ms, 70, inv, win);
}
void print_stats(inventory_t *inv, window_t *win)
{
sfText_setColor(inv->stat_txt->text, sfColor_fromRGB(200, 200, 200));
if (inv->items[inv->s_index] != NULL && inv->stock == NULL)
put_weapon_info(inv->items[inv->s_index], inv, win, 0);
if (inv->items[inv->s_index] == NULL && inv->stock != NULL)
put_weapon_info(inv->stock, inv, win, 0);
if (inv->items[inv->s_index] != NULL && inv->stock != NULL
&& inv->items[inv->s_index2] == NULL)
put_weapon_info(inv->stock, inv, win, 0);
if (inv->items[inv->s_index] != NULL && inv->stock != NULL
&& inv->items[inv->s_index2] != NULL) {
put_weapon_info(inv->stock, inv, win, 0);
put_weapon_info(inv->items[inv->s_index], inv, win, 70);
put_diff(inv, win);
}
}<file_sep>/*
** EPITECH PROJECT, 2020
** mod_f
** File description:
** mod_f
*/
#include "../my_printf.h"
void print_mod_f(double nb)
{
unsigned long long nbr = nb * 1000000;
int len = 0;
for (int i = nbr; i > 9; len++, i /= 10);
for (; len >= 6; len--)
my_put_nbr_p(nbr / my_pow(10, len) % 10);
my_putchar_p('.');
for (; len >= 0; len--)
my_put_nbr_p(nbr / my_pow(10, len) % 10);
}
<file_sep>/*
** EPITECH PROJECT, 2021
** create_player
** File description:
** create_player
*/
#include "rpg.h"
player_t *create_player2(player_t *player)
{
player->orb = malloc(sizeof(object_t) * 5);
for (int i = 0; i < 5; ++i)
player->orb[i] = NULL;
player->press_space = create_object("image/press_space.png", 0, 0);
player->pstat_page = create_object("image/pstat_page.png", 200, 300);
player->stat_txt = create_text2("yo", 0, 0, 70);
return player;
}
player_t *create_player(void)
{
player_t *player = malloc(sizeof(player_t));
player->object = malloc(sizeof(object_t));
player->shoot = malloc(sizeof(shoot_t *) * 10);
for (int i = 0; i < 10; i++)
player->shoot[i] = NULL;
player->shootdir = 2;
player->weapon = malloc(sizeof(weapon_t));
player->stats = init_pstats();
player->object = create_object("./image/player.png", 940, 420);
player->object = init_rect(player->object, 100, 134, 268);
player->object->clock = sfClock_create();
player->direction = 4;
player->lim = 300;
player->inv = create_inventory(player->inv, player->object->pos);
player->weapon = create_glock(player->inv->items[21],
player->inv, 21);
player->speed = 6;
player = create_player2(player);
return player;
}<file_sep>/*
** EPITECH PROJECT, 2021
** orb
** File description:
** orb
*/
#include "rpg.h"
void is_space_pressed(window_t *win, object_t **orb, player_t *player, int i)
{
if (sfKeyboard_isKeyPressed(sfKeySpace) == sfTrue) {
if (player->stats->life <= player->stats->max_life - 20) {
player->stats->life += 20;
} else if (player->stats->life > player->stats->max_life - 20
&& player->stats->life != player->stats->max_life)
player->stats->life += player->stats->max_life
- player->stats->life;
sfSound_play(win->sound->list[0]);
orb[i] = NULL;
}
}
player_t *update_orb_pos(window_t *win, object_t **orb, player_t *player)
{
player->press_space = init_pos(player->press_space,
player->object->pos.x - 20, player->object->pos.y - 20);
for (int i = 0; i < 5; ++i)
if (orb[i] != NULL) {
orb[i]->pos.x += win->mvmnt.x;
orb[i]->pos.y += win->mvmnt.y;
sfSprite_setPosition(orb[i]->sprite, orb[i]->pos);
}
return player;
}
player_t *heal(window_t *win, object_t **orb, player_t *player)
{
for (int i = 0; i < 5; i++)
if (orb[i] != NULL) {
draw(win->window, orb[i]->sprite);
animation(orb[i], 80, 1360, 200);
}
for (int i = 0; i < 5 && orb[i] != NULL; ++i)
if (player->object->pos.x < orb[i]->pos.x + 80
&& player->object->pos.x + 100 > orb[i]->pos.x
&& player->object->pos.y < orb[i]->pos.y + 60
&& player->object->pos.y + 134 > orb[i]->pos.y) {
draw(win->window, player->press_space->sprite);
is_space_pressed(win, orb, player, i);
}
player = update_orb_pos(win, orb, player);
return player;
}
object_t **create_orb(object_t **orb, ennemy_t *ennemy)
{
int random = rand() % 101;
int spawn_orb = 0;
if (random <= 30)
spawn_orb = 1;
for (int i = 0; i < 5 && spawn_orb == 1; ++i)
if (orb[i] == NULL) {
orb[i] = create_object("image/orb.png",
ennemy->list->object->pos.x, ennemy->list->object->pos.y);
orb[i] = init_rect(orb[i], 80, 60, 0);
orb[i]->clock = sfClock_create();
break;
}
return orb;
}<file_sep>/*
** EPITECH PROJECT, 2020
** issam
** File description:
** .h
*/
#ifndef RPG_H_
#define RPG_H_
#include <stdio.h>
#include <stdlib.h>
#include <SFML/Graphics.h>
#include <SFML/Window.h>
#include <SFML/Window/Event.h>
#include <SFML/Audio.h>
#include <SFML/System.h>
#include <SFML/System/Vector2.h>
#include <SFML/Graphics/Texture.h>
#include <SFML/Window/Types.h>
#include <SFML/Window/Mouse.h>
#include <SFML/Window/Export.h>
#include <SFML/Audio/Types.h>
#include <SFML/Audio/SoundStatus.h>
#include <SFML/Audio/Export.h>
#include <SFML/Audio.h>
#include <time.h>
#include "my.h"
typedef struct object_s {
sfTexture *texture;
sfSprite *sprite;
sfVector2f pos;
sfClock *clock;
sfIntRect rect;
sfVector2f scale;
int plus;
int open;
int is_closed;
}object_t;
typedef struct rect_s {
sfRectangleShape *rect;
sfVector2f pos;
sfVector2f size;
}rect_t;
typedef struct text_s {
sfText *text;
sfVector2f pos;
}text_t;
typedef struct shoot_s {
sfTexture *texture;
sfSprite *sprite;
sfVector2f pos;
int direction;
sfClock *clock;
sfIntRect rect;
int anim;
int dmg;
}shoot_t;
typedef struct weapon_s {
sfClock *clock;
int type;
int ms;
int canshoot;
int dmg;
int index;
object_t *object;
}weapon_t;
typedef struct ennemis_l {
struct ennemis_l *next;
struct ennemis_l *prev;
int can_attack;
int lvl;
int life;
int speed;
int dmg;
sfClock *attack_clock;
object_t *object;
}en_list;
typedef struct ennemy_s {
en_list *list;
en_list *start;
rect_t *rect;
text_t *txt;
}ennemy_t;
typedef struct chest_s {
int id;
int open;
}chest_t;
typedef struct level_s {
char ***maps;
sfVector2f *spawns;
sfVector2f *warps;
int lvl;
ennemy_t **ennemy;
object_t ***chests;
}level_t;
typedef struct pstats_s {
object_t *lvl_up;
rect_t *rect;
int launch_lvlup;
int max_life;
int life;
int lvl;
int dmg;
int armor;
int xp;
}pstats_t;
typedef struct inventory_s {
object_t *object;
object_t *hotbar;
object_t *stat_b;
object_t *trash;
weapon_t **items;
rect_t *rect;
rect_t *hotrect;
rect_t *mini_rect;
weapon_t *stock;
text_t *stat_txt;
int s_index;
int s_index2;
int prev_index;
int is_swapping;
int **slot_pos;
int display;
int index;
}inventory_t;
typedef struct quest_l {
object_t *chatbox;
object_t *eugena;
object_t *hello;
object_t *abandon;
object_t *touches;
object_t *goodluck;
object_t *presse;
object_t *pressenter;
int mod;
}quest_t;
typedef struct sound_s {
sfMusic *music;
sfSound **list;
}sound_t;
typedef struct window_s {
sfRenderWindow *window;
quest_t *quest;
sfEvent event;
sfVector2i mouse;
sfVector2f map_pos;
sfVector2f mvmnt;
int mod;
char **map;
char *pth;
int fps;
sound_t *sound;
object_t *trans;
object_t *back;
object_t *sound_m;
object_t *sound_g;
object_t *setting;
object_t *win_screen;
float snd;
int transcolor;
int t_state;
int t_mod;
int l_state;
int l_mod;
}window_t;
typedef struct object_list {
object_t *starback;
object_t *mnlunar;
object_t *exit;
object_t *info;
object_t *param;
object_t *start;
object_t *bigstart;
object_t *sure;
object_t *menuparam;
object_t *info_one;
object_t *info_two;
int mod;
}object_l;
typedef struct lose_s {
object_t *game_over;
object_t *skin;
object_t *exit;
object_t *home;
}lose_t;
typedef struct player_s {
object_t *object;
shoot_t **shoot;
weapon_t *weapon;
inventory_t *inv;
pstats_t *stats;
object_t **orb;
object_t *press_space;
object_t *pstat_page;
text_t *stat_txt;
int speed;
int direction;
int shootdir;
sfVector2f shootpos;
int lim;
}player_t;
typedef struct pbl_s {
object_l *menu;
player_t *player;
level_t *lvl;
lose_t *lose;
sfSprite **ground;
sfView *view;
sfVector2f view_size;
sfSprite **tp;
sfClock *tp_clock;
}pbl_t;
window_t *create_window(void);
object_t *create_object(char *pth, int x, int y);
text_t *create_text(char *str, int x, int y, int size);
text_t *create_text2(char *str, int x, int y, int size);
object_t *init_rect(object_t *object, int width, int height, int top);
object_t *init_pos(object_t *object, int x, int y);
void animation(object_t *object, int mv, int lim, float ms);
int main(void);
void draw(sfRenderWindow *window, sfSprite *sprite);
/*MENU*/
object_l *create_mm_sprites(void);
void transition(window_t *win);
void launch_transition(window_t *win, int mod);
void main_menu(object_l *menu, window_t *win);
lose_t *init_lose(void);
void do_lose(window_t *win, lose_t *lose);
void draw_main_menu(object_l *menu, window_t *win);
quest_t *create_quest(void);
void draw_quest(window_t *win, quest_t *quest);
void my_pause(object_l *menu, window_t *win);
void my_fps(window_t *win);
void my_info(object_l *menu, window_t *win);
void controle_menu_sound(object_l *menu, window_t *win);
void controle_game_sound(object_l *menu, window_t *win);
/*PLAYER*/
player_t *create_player(void);
shoot_t *create_bullet(char *pth, player_t *player, int x, int y);
inventory_t *create_inventory(inventory_t *inv, sfVector2f pos);
inventory_t *generate_weapon(inventory_t *inv);
inventory_t *swap_items(inventory_t *inv, window_t *win);
player_t *put_rect(player_t *player, int nb);
weapon_t *create_glock(weapon_t *item, inventory_t *inv, int i);
weapon_t *create_rifle(weapon_t *item, inventory_t *inv, int i);
weapon_t *create_snipe(weapon_t *item, inventory_t *inv, int i);
player_t *destroy_bullet(player_t *player, int i);
shoot_t *init_bullet_rect(shoot_t *object, int width, int height, int top);
player_t *switch_weapons(inventory_t *inv, player_t *player, window_t *win);
object_t **create_orb(object_t **orb, ennemy_t *ennemy);
player_t *heal(window_t *win, object_t **orb, player_t *player);
pstats_t *init_pstats(void);
pstats_t *update_stats(window_t *win, pstats_t *stats);
void mv_win2(player_t *player, window_t *win, pbl_t * game);
void display_xp_life(window_t *win, player_t *player);
void display_pstart(window_t *win, player_t *player);
int collision_with_wall(pbl_t *game, window_t *win, int dirx, int diry);
void animate_player(player_t *player, window_t *win, pbl_t *game);
void animat_bullet(shoot_t *object, int mv, int lim, float ms);
void shoot(player_t *player, window_t *window);
void inventory_display(player_t *player, window_t *win);
void draw_inv_weapons(inventory_t *inv, window_t *win);
void draw_hot_weapons(inventory_t *inv, window_t *win);
void draw_minimap(window_t *win, level_t *lvl, player_t *player);
void shake(player_t *player);
void print_stats(inventory_t *inv, window_t *win);
/*ENNEMY*/
ennemy_t **create_all_ennemies(level_t *lvl);
ennemy_t *init_ennemies(void);
ennemy_t *ennemies_hb(window_t *win, ennemy_t *ennemy, player_t *player);
en_list *create_en_object(int lvl, en_list *list);
void draw_en_lifebarre(window_t *win, ennemy_t *ennemy);
void mv_ennemies(window_t *win, ennemy_t *ennemy, player_t *player);
/*CHESTS*/
object_t ***create_all_chests(level_t *lvl);
void draw_chests(window_t *win, level_t *lvl, player_t *player);
int open_chest(window_t *win, level_t *lvl, player_t *player, int i);
/*LEVEL*/
level_t *create_level_memory(void);
level_t *create_level(void);
void lvl_transition(window_t *win, level_t *lvl, player_t *player, pbl_t *game);
ennemy_t *create_ennemies(level_t *lvl, int nm, int x_spawn, int y_spawn);
void mode(pbl_t *game, window_t *win);
/*MAP*/
sfSprite **create_chest(char *path);
sfSprite **create_map(char *path);
sfSprite **create_teleport(char *path);
void draw_ground(window_t *win, pbl_t *game, level_t *lvl);
/*AUDIO*/
sound_t *init_audio(void);
sfSound **init_sound(void);
sfSound *create_sound(char *path);
#endif<file_sep>/*
** EPITECH PROJECT, 2020
** Untitled (Workspace)
** File description:
** my_strncpy.c
*/
char *my_strncpy(char *dest, char const *src, int n_1, int n_2)
{
int t = 0;
for (int i = n_1; i < (n_2 + n_1); i++, t++)
dest[t] = src[i];
dest[t] = '\0';
return dest;
}
<file_sep>/*
** EPITECH PROJECT, 2019
** my_itoa.c
** File description:
** my_itoa
*/
#include <stddef.h>
#include <stdlib.h>
#include "my.h"
static int my_int_len(int nb)
{
int count = 1;
for (int div = 1; nb / div >= 1; div *= 10, count++);
return count;
}
char *my_itoa(int nb)
{
if (nb < 0)
nb *= -1;
else if (nb == 0)
return "0\0";
int i = my_int_len(nb) - 1;
char *str = malloc(sizeof(char) * (i + 1));
if (str == NULL)
return NULL;
str[i] = '\0';
for (; i > 0; nb /= 10, i--)
str[i - 1] = (nb % 10) + '0';
if (str[0] == '\0')
str = my_strcpy("\0", "0\0");
return str;
}
<file_sep>/*
** EPITECH PROJECT, 2020
** my_printf.h
** File description:
** my_printf.h
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
void print_octal_s(unsigned int ascii);
void my_putchar_p(char c);
void my_putstr_p(char const *str);
void my_putstr_octal_p(char const *str);
void my_put_nbr_p(long nb);
char *my_revstr(char *str);
void print_mod(int i, char *str, va_list ap);
int my_getnbr(char const *str);
char *my_getstr(int nb);
int my_pow(int nb, int pow);
void print_binary(int nb);
void print_hexa(int nb, int mod);
void print_octal_o(int nb);
void print_mod_e(double nb);
int get_number(double n, unsigned long long nbr);
int *get_arr(int *arr, double nb, unsigned long long nbr);
void print_mod_cape(double nb);
void print_mod_f(double nb);
<file_sep>/*
** EPITECH PROJECT, 2020
** print_binary
** File description:
** print_binary
*/
#include "../my_printf.h"
void print_binary(int nb)
{
int len = 0;
char *binary;
int i = nb;
for (; i != 0; len++, i /= 2);
binary = malloc(sizeof(char) * (len + 1));
for (int t = 0; nb != 0; nb /= 2, t++)
binary[t] = (nb % 2) + '0';
my_putstr_p(my_revstr(binary));
}
<file_sep>/*
** EPITECH PROJECT, 2021
** openmap
** File description:
** openmap
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include "my.h"
int *get_size(char *buffer)
{
int *arr = malloc(sizeof(int) * 2);
int t = 0, z = 0;
for (int i = 0, a = 0; buffer[i] != '\0'; i++) {
if (buffer[i] == '\n') {
z = a > z ? a : z;
t++;
a = 0;
} else
a++;
}
arr[0] = t;
arr[1] = z;
return arr;
}
char **buffer_to_char(char *buffer)
{
char **map = NULL;
int *arr = get_size(buffer);
map = malloc(sizeof(char *) * arr[0]);
for (int i = 0; i < arr[0]; i++)
map[i] = (char *) malloc(sizeof(char) * arr[1]);
for (int q = 0, k = 0, c = 0; buffer[q] != '\0'; q++) {
if (buffer[q] == '\n') {
map[k][c] = '\0';
k++;
c = 0;
} else {
map[k][c] = buffer[q];
c++;
}
}
map[arr[0]] = NULL;
return (map);
}
char **open_map(char *pth)
{
struct stat buf;
size_t buffsize;
stat(pth, &buf);
char *str_tmp = malloc(sizeof(char) * buf.st_size);
FILE *fd = fopen(pth, "r");
char *buff = NULL;
while (getline(&buff, &buffsize, fd) != -1)
my_strcat(str_tmp, buff);
str_tmp[buf.st_size - 1] = '\n';
str_tmp[buf.st_size] = '\0';
char **buffer = buffer_to_char(str_tmp);
return buffer;
}<file_sep>/*
** EPITECH PROJECT, 2021
** display_pstart
** File description:
** display_pstart
*/
#include "rpg.h"
void display_life(window_t *win, player_t *player)
{
sfText_setCharacterSize(player->stat_txt->text, 30);
sfText_setColor(player->stat_txt->text, sfColor_fromRGB(139, 0, 0));
player->stat_txt->pos.x = 1380;
player->stat_txt->pos.y = 16;
sfText_setString(player->stat_txt->text, my_itoa(player->stats->life));
sfText_setPosition(player->stat_txt->text, player->stat_txt->pos);
sfRenderWindow_drawText(win->window, player->stat_txt->text, NULL);
player->stat_txt->pos.x = 1440;
player->stat_txt->pos.y = 16;
sfText_setString(player->stat_txt->text, "/");
sfText_setPosition(player->stat_txt->text, player->stat_txt->pos);
sfRenderWindow_drawText(win->window, player->stat_txt->text, NULL);
player->stat_txt->pos.x = 1470;
player->stat_txt->pos.y = 16;
sfText_setString(player->stat_txt->text, my_itoa(player->stats->max_life));
sfText_setPosition(player->stat_txt->text, player->stat_txt->pos);
sfRenderWindow_drawText(win->window, player->stat_txt->text, NULL);
}
void display_xp(window_t *win, player_t *player)
{
sfText_setCharacterSize(player->stat_txt->text, 30);
sfText_setColor(player->stat_txt->text, sfColor_fromRGB(0, 132, 0));
player->stat_txt->pos.x = 1420;
player->stat_txt->pos.y = 67;
sfText_setString(player->stat_txt->text, my_itoa(player->stats->xp));
sfText_setPosition(player->stat_txt->text, player->stat_txt->pos);
sfRenderWindow_drawText(win->window, player->stat_txt->text, NULL);
player->stat_txt->pos.x = 1460;
player->stat_txt->pos.y = 67;
sfText_setString(player->stat_txt->text, "/");
sfText_setPosition(player->stat_txt->text, player->stat_txt->pos);
sfRenderWindow_drawText(win->window, player->stat_txt->text, NULL);
player->stat_txt->pos.x = 1490;
player->stat_txt->pos.y = 67;
sfText_setString(player->stat_txt->text, my_itoa(player->stats->lvl * 2));
sfText_setPosition(player->stat_txt->text, player->stat_txt->pos);
sfRenderWindow_drawText(win->window, player->stat_txt->text, NULL);
}
void display_lvl(window_t *win, player_t *player)
{
sfText_setCharacterSize(player->stat_txt->text, 50);
sfText_setColor(player->stat_txt->text, sfColor_fromRGB(200, 200, 200));
player->stat_txt->pos.x = 440;
player->stat_txt->pos.y = 390;
sfText_setString(player->stat_txt->text, "lvl:");
sfText_setPosition(player->stat_txt->text, player->stat_txt->pos);
sfRenderWindow_drawText(win->window, player->stat_txt->text, NULL);
player->stat_txt->pos.x = 530;
player->stat_txt->pos.y = 390;
sfText_setString(player->stat_txt->text, my_itoa(player->stats->lvl));
sfText_setPosition(player->stat_txt->text, player->stat_txt->pos);
sfRenderWindow_drawText(win->window, player->stat_txt->text, NULL);
}
void display_pstart(window_t *win, player_t *player)
{
draw(win->window, player->pstat_page->sprite);
display_lvl(win, player);
sfText_setCharacterSize(player->stat_txt->text, 60);
sfText_setColor(player->stat_txt->text, sfColor_fromRGB(200, 200, 200));
player->stat_txt->pos.x = 440;
player->stat_txt->pos.y = 465;
sfText_setString(player->stat_txt->text, my_itoa(player->speed));
sfText_setPosition(player->stat_txt->text, player->stat_txt->pos);
sfRenderWindow_drawText(win->window, player->stat_txt->text, NULL);
player->stat_txt->pos.x = 440;
player->stat_txt->pos.y = 585;
sfText_setString(player->stat_txt->text, my_itoa(player->stats->armor));
sfText_setPosition(player->stat_txt->text, player->stat_txt->pos);
sfRenderWindow_drawText(win->window, player->stat_txt->text, NULL);
player->stat_txt->pos.x = 440;
player->stat_txt->pos.y = 705;
sfText_setString(player->stat_txt->text, my_itoa(player->stats->dmg));
sfText_setPosition(player->stat_txt->text, player->stat_txt->pos);
sfRenderWindow_drawText(win->window, player->stat_txt->text, NULL);
}
void display_xp_life(window_t *win, player_t *player)
{
display_life(win, player);
display_xp(win, player);
}<file_sep>/*
** EPITECH PROJECT, 2020
** my_putstr
** File description:
** my_putstr
*/
#include "../my_printf.h"
void my_putstr_p(char const *str)
{
for (int x = 0; str[x] != '\0'; x++)
my_putchar_p(str[x]);
}
void my_putstr_octal_p(char const *str)
{
for (int x = 0; str[x] != '\0'; x++) {
if (str[x] < 32 || str[x] > 127)
print_octal_s(str[x]);
else
my_putchar_p(str[x]);
}
}
<file_sep>/*
** EPITECH PROJECT, 2021
** ennemies
** File description:
** ennemeis
*/
#include "rpg.h"
void draw_ennemies(window_t *win, ennemy_t *ennemy)
{
while (ennemy->list->next->next != NULL) {
if (ennemy->list->life > 0) {
ennemy->list->object->pos.x += win->mvmnt.x;
ennemy->list->object->pos.y += win->mvmnt.y;
sfSprite_setPosition(ennemy->list->object->sprite,
ennemy->list->object->pos);
draw(win->window, ennemy->list->object->sprite);
animation(ennemy->list->object, 96, 576, 200.0);
}
ennemy->list = ennemy->list->next;
}
win->mvmnt.x = 0;
win->mvmnt.y = 0;
ennemy->list = ennemy->start;
}
int check_agro_hb(ennemy_t *ennemy, player_t *player)
{
if (player->object->pos.x + 100 > ennemy->list->object->pos.x - 300
&& player->object->pos.x < ennemy->list->object->pos.x + 396
&& player->object->pos.y + 134 > ennemy->list->object->pos.y - 300
&& player->object->pos.y < ennemy->list->object->pos.y + 396)
return 1;
return 0;
}
ennemy_t *set_direction(ennemy_t *ennemy, player_t *player)
{
if (player->object->pos.y > ennemy->list->object->pos.y)
ennemy->list->object->rect.top = 2;
if (player->object->pos.y < ennemy->list->object->pos.y)
ennemy->list->object->rect.top = 290;
if (player->object->pos.x > ennemy->list->object->pos.x)
ennemy->list->object->rect.top = 186;
if (player->object->pos.x < ennemy->list->object->pos.x)
ennemy->list->object->rect.top = 100;
sfSprite_setTextureRect(ennemy->list->object->sprite,
ennemy->list->object->rect);
return ennemy;
}
ennemy_t *mvmnt(ennemy_t *ennemy, player_t *player)
{
int x = player->object->pos.x - ennemy->list->object->pos.x;
int y = player->object->pos.y - ennemy->list->object->pos.y;
if (x < 0)
x *= -1;
if (y < 0)
y *= -1;
if (player->object->pos.x > ennemy->list->object->pos.x)
ennemy->list->object->pos.x += ennemy->list->speed;
if (player->object->pos.x < ennemy->list->object->pos.x)
ennemy->list->object->pos.x -= ennemy->list->speed;
if (player->object->pos.y + 23 > ennemy->list->object->pos.y)
ennemy->list->object->pos.y += ennemy->list->speed;
if (player->object->pos.y + 23 < ennemy->list->object->pos.y)
ennemy->list->object->pos.y -= ennemy->list->speed;
sfSprite_setPosition(ennemy->list->object->sprite,
ennemy->list->object->pos);
return ennemy;
}
void mv_ennemies(window_t *win, ennemy_t *ennemy, player_t *player)
{
while (ennemy->list->next->next != NULL) {
if (ennemy->list->life > 0 && check_agro_hb(ennemy, player) == 1) {
ennemy = mvmnt(ennemy, player);
ennemy = set_direction(ennemy, player);
draw_en_lifebarre(win, ennemy);
ennemy = ennemies_hb(win, ennemy, player);
}
ennemy->list = ennemy->list->next;
}
ennemy->list = ennemy->start;
draw_ennemies(win, ennemy);
}<file_sep>/*
** EPITECH PROJECT, 2021
** mode
** File description:
** mode
*/
#include "rpg.h"
static sfSprite *anim_tp(sfSprite **tp, sfClock *clock, sfVector2f pos, int rs)
{
static int i = 0;
sfTime time = sfClock_getElapsedTime(clock);
pos.x -= 80;
pos.y -= 14;
if (rs != 1)
i = 0;
else if (time.microseconds / 100000.0 > 1) {
if (tp[i + 1] == NULL)
i = 0;
++i;
sfClock_restart(clock);
}
sfSprite_setPosition(tp[i], pos);
return tp[i];
}
static void draw_sprite(window_t *win, pbl_t *game, char c, sfVector2f pos)
{
if (c >= 'A' && c <= 'P') {
sfSprite_setPosition(game->ground[c - 'A'], pos);
draw(win->window, game->ground[c - 'A']);
} else if (c == '3' || c == '0') {
sfSprite_setPosition(game->ground['F' - 'A'], pos);
draw(win->window, game->ground['F' - 'A']);
}
}
void draw_ground(window_t *win, pbl_t *game, level_t *lvl)
{
sfVector2f pos = {win->map_pos.x, win->map_pos.y};
sfVector2f tp_pos;
char **map = lvl->maps[lvl->lvl];
int nb = 0;
win->back->pos.x = (win->map_pos.x / 2) - 700;
win->back->pos.y = (win->map_pos.y / 2) - 300;
sfSprite_setPosition(win->back->sprite, win->back->pos);
draw(win->window, win->back->sprite);
for (int x = 0; map[x] != NULL; pos.x = win->map_pos.x, pos.y += 96.0, ++x)
for (int y = 0; map[x][y] != '\0'; pos.x += 96.0, ++y) {
if (map[x][y] == '0')
tp_pos = pos;
if (map[x][y] == '2') {
sfSprite_setPosition(game->ground['F' - 'A'], pos);
draw(win->window, game->ground['F' - 'A']);
}
draw_sprite(win, game, map[x][y], pos);
}
draw(win->window, anim_tp(game->tp, game->tp_clock, tp_pos, win->l_state));
}<file_sep>/*
** EPITECH PROJECT, 2020
** print_octal
** File description:
** print_octal
*/
#include "../my_printf.h"
void print_octal_s(unsigned int ascii)
{
char *str = malloc(sizeof(char) * 12);
unsigned int oct = 1;
unsigned int rest = 1;
int i = 0;
for (; ascii != 0; i++) {
str[i] = (ascii - ((ascii / 8) * 8)) + '0';
ascii /= 8;
}
str[i] = '\0';
my_putstr_p("\\0");
if (my_getnbr(my_revstr(str)) < 10)
my_putchar_p('0');
my_putstr_p(str);
}
void print_octal_o(int nb)
{
int div = 0;
for (int times = 1, min; nb != 0; nb -= min) {
div = 0;
times = 1;
for (; my_pow(8, (div + 1)) <= nb; div++);
for (; (times + 1) * my_pow(8, div) <= nb; times++);
my_put_nbr_p(times);
min = times * my_pow(8, div);
}
for (; div != 0; div--)
my_putchar_p('0');
}
<file_sep>/*
** EPITECH PROJECT, 2021
** weapons
** File description:
** weapons
*/
#include "rpg.h"
inventory_t *generate_weapon(inventory_t *inv)
{
int i = 0;
for (; inv->items[i] != NULL; ++i);
if (i < 21) {
inv->items[i] = malloc(sizeof(weapon_t));
inv->items[i]->type = rand() % 3;
if (inv->items[i]->type == 0)
inv->items[i] = create_glock(inv->items[i] , inv, i);
else if (inv->items[i]->type == 2)
inv->items[i] = create_rifle(inv->items[i] , inv, i);
else
inv->items[i] = create_snipe(inv->items[i] , inv, i);
}
return inv;
}
int find_slot(inventory_t *inv, window_t *win)
{
for (int i = 0; i < 25; i++)
if (win->mouse.x >= inv->slot_pos[i][0]
&& win->mouse.x <= inv->slot_pos[i][0] + 79
&& win->mouse.y >= inv->slot_pos[i][1]
&& win->mouse.y <= inv->slot_pos[i][1] + 78)
return i;
return -1;
}
inventory_t *drop(inventory_t *inv, window_t *win)
{
int swap = 0;
if (inv->is_swapping == 0 && inv->stock != NULL) {
swap = find_slot(inv, win);
if (swap == -1)
inv->items[inv->index] = inv->stock;
if (swap != -1 && inv->items[swap] != NULL && inv->stock != NULL) {
inv->items[inv->prev_index] = inv->items[swap];
inv->items[swap] = inv->stock;
}
if (swap != -1 && inv->items[swap] == NULL)
inv->items[swap] = inv->stock;
inv->stock = NULL;
}
inv->items[24] = NULL;
return inv;
}
player_t *switch_weapons(inventory_t *inv, player_t *player, window_t *win)
{
if (sfKeyboard_isKeyPressed(sfKeyNum1) == sfTrue && inv->items[21])
player = put_rect(player, 21);
if (sfKeyboard_isKeyPressed(sfKeyNum2) == sfTrue && inv->items[22])
player = put_rect(player, 22);
if (sfKeyboard_isKeyPressed(sfKeyNum3) == sfTrue && inv->items[23])
player = put_rect(player, 23);
sfRectangleShape_setPosition(player->inv->hotrect->rect,
player->inv->hotrect->pos);
if (player->inv->display != 1)
sfRenderWindow_drawRectangleShape(win->window,
player->inv->hotrect->rect, NULL);
return player;
}
inventory_t *swap_items(inventory_t *inv, window_t *win)
{
if (inv->is_swapping == 1 && sfMouse_isButtonPressed(sfMouseLeft) == sfTrue
&& inv->items[inv->index] != NULL && inv->stock == NULL) {
inv->stock = inv->items[inv->index];
inv->items[inv->index] = NULL;
inv->prev_index = inv->index;
}
if (inv->stock != NULL) {
init_pos(inv->stock->object, win->mouse.x - 37, win->mouse.y - 35);
draw(win->window, inv->stock->object->sprite);
}
inv = drop(inv, win);
if (sfMouse_isButtonPressed(sfMouseLeft) == sfFalse)
inv->is_swapping = 0;
return inv;
}<file_sep>/*
** EPITECH PROJECT, 2021
** ennemies hitbox
** File description:
** ennemies hitbox
*/
#include "rpg.h"
int shoot_hb(ennemy_t *ennemy, player_t *player, int i)
{
if (player->shoot[i]->anim == 70
&& player->shoot[i]->pos.x < ennemy->list->object->pos.x + 96
&& player->shoot[i]->pos.x + 70 > ennemy->list->object->pos.x
&& player->shoot[i]->pos.y < ennemy->list->object->pos.y + 96
&& player->shoot[i]->pos.y + 55 > ennemy->list->object->pos.y)
return 1;
if (player->shoot[i]->anim == 55
&& player->shoot[i]->pos.x < ennemy->list->object->pos.x + 96
&& player->shoot[i]->pos.x + 55 > ennemy->list->object->pos.x
&& player->shoot[i]->pos.y < ennemy->list->object->pos.y + 96
&& player->shoot[i]->pos.y + 70 > ennemy->list->object->pos.y)
return 1;
return 0;
}
void draw_en_lifebarre(window_t *win, ennemy_t *ennemy)
{
ennemy->txt->pos.x = ennemy->list->object->pos.x + 20;
ennemy->txt->pos.y = ennemy->list->object->pos.y - 30;
sfText_setString(ennemy->txt->text, "lvl:");
sfText_setPosition(ennemy->txt->text, ennemy->txt->pos);
sfRenderWindow_drawText(win->window, ennemy->txt->text, NULL);
ennemy->txt->pos.x = ennemy->list->object->pos.x + 45;
ennemy->txt->pos.y = ennemy->list->object->pos.y - 30;
sfText_setString(ennemy->txt->text, my_itoa(ennemy->list->lvl + 1));
sfText_setPosition(ennemy->txt->text, ennemy->txt->pos);
sfRenderWindow_drawText(win->window, ennemy->txt->text, NULL);
ennemy->rect->pos.x = ennemy->list->object->pos.x + 10;
ennemy->rect->pos.y = ennemy->list->object->pos.y - 10;
sfRectangleShape_setPosition(ennemy->rect->rect, ennemy->rect->pos);
ennemy->rect->size.x = 50 * ennemy->list->life / 100;
sfRectangleShape_setSize(ennemy->rect->rect, ennemy->rect->size);
sfRenderWindow_drawRectangleShape(win->window, ennemy->rect->rect, NULL);
}
player_t *ennemy_attack(window_t *win, ennemy_t *ennemy, player_t *player)
{
sfTime time = sfClock_getElapsedTime(ennemy->list->attack_clock);
if ((time.microseconds / (1000000.0)) > 1) {
ennemy->list->can_attack = 1;
sfClock_restart(ennemy->list->attack_clock);
}
if (player->object->pos.x < ennemy->list->object->pos.x + 76
&& player->object->pos.x + 100 > ennemy->list->object->pos.x + 20
&& player->object->pos.y < ennemy->list->object->pos.y + 76
&& player->object->pos.y + 134 > ennemy->list->object->pos.y + 20
&& ennemy->list->can_attack == 1) {
sfSound_play(win->sound->list[4]);
player->stats->life -= ennemy->list->dmg - player->stats->armor;
ennemy->list->can_attack = 0;
}
return player;
}
ennemy_t *ennemies_hb(window_t *win, ennemy_t *ennemy, player_t *player)
{
int last_life = 0;
for (int i = 0; i < 10; i++) {
if (player->shoot[i] != NULL && shoot_hb(ennemy, player, i) == 1) {
last_life = ennemy->list->life;
ennemy->list->life -= player->weapon->dmg + player->stats->dmg;
player->shoot[i] = NULL;
if (last_life > 0 && ennemy->list->life <= 0) {
player->stats->xp++;
player->orb = create_orb(player->orb, ennemy);
}
}
}
player = ennemy_attack(win, ennemy, player);
return ennemy;
}<file_sep>/*
** EPITECH PROJECT, 2020
** my_printf
** File description:
** my_printf
*/
#include "my_printf.h"
void *my_printf(char *str, ...)
{
va_list ap;
va_start(ap, str);
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == '%') {
print_mod(i, str, ap);
i++;
} else
my_putchar_p(str[i]);
}
va_end(ap);
}
<file_sep>/*
** EPITECH PROJECT, 2021
** create_ennemies
** File description:
** create_ennemies
*/
#include "rpg.h"
ennemy_t *go_next(ennemy_t *ennemy)
{
en_list *tmp = ennemy->list;
ennemy->list->next = malloc(sizeof(en_list));
ennemy->list = ennemy->list->next;
ennemy->list->prev = tmp;
return ennemy;
}
ennemy_t *create_en_lifebarre(ennemy_t *ennemy)
{
ennemy->txt = create_text2("c'est rien cest la rue", 0, 0, 15);
ennemy->rect = malloc(sizeof(rect_t));
ennemy->rect->rect = sfRectangleShape_create();
sfColor outcolor = sfColor_fromRGBA(8, 98, 175, 200);
sfColor incolor = sfColor_fromRGBA(8, 98, 175, 200);
ennemy->rect->size.x = 50;
ennemy->rect->size.y = 10;
sfRectangleShape_setSize(ennemy->rect->rect, ennemy->rect->size);
sfRectangleShape_setOutlineColor(ennemy->rect->rect, outcolor);
sfRectangleShape_setFillColor(ennemy->rect->rect, incolor);
sfRectangleShape_setOutlineThickness(ennemy->rect->rect, 1);
return ennemy;
}
ennemy_t *init_ennemies(void)
{
ennemy_t *ennemy = malloc(sizeof(ennemy_t));
ennemy = create_en_lifebarre(ennemy);
ennemy->list = malloc(sizeof(en_list));
ennemy->list->prev = NULL;
ennemy->start = ennemy->list;
return ennemy;
}
ennemy_t *create_ennemies(level_t *lvl, int nm, int x_spawn, int y_spawn)
{
ennemy_t *ennemy = init_ennemies();
for (int i = 1, nb = 0; lvl->maps[lvl->lvl][i] != NULL; i++) {
for (int t = 0; lvl->maps[lvl->lvl][i][t] != '\0'; t++) {
if (rand() % 1000 < nm && lvl->maps[lvl->lvl][i][t] == 'F') {
ennemy->list = create_en_object(lvl->lvl, ennemy->list);
ennemy->list->object = init_pos(ennemy->list->object,
t * 96 + x_spawn - 946, i * 96 + y_spawn - 474);
ennemy = go_next(ennemy);
}
}
}
ennemy->list->next = NULL;
ennemy->list = ennemy->start;
return ennemy;
}
ennemy_t **create_all_ennemies(level_t *lvl)
{
ennemy_t **all_ennemies = malloc(sizeof(ennemy_t *) * 12);
all_ennemies[0] = create_ennemies(lvl, 0, 0.0, 0.0);
return all_ennemies;
}<file_sep>/*
** EPITECH PROJECT, 2020
** B-MUL-200-PAR-2-1-myrpg-julien.de-waele
** File description:
** my_pause.c
*/
#include "rpg.h"
void my_fps(window_t *win)
{
if (win->mouse.x >= 659 && win->mouse.y >= 476
&& win->mouse.x <= 679 && win->mouse.y <= 496 &&
sfMouse_isButtonPressed(sfMouseLeft) == sfTrue) {
win->fps = 30;
sfRenderWindow_setFramerateLimit(win->window, win->fps);
}
if (win->mouse.x >= 948 && win->mouse.y >= 478
&& win->mouse.x <= 468 && win->mouse.y <= 497 &&
sfMouse_isButtonPressed(sfMouseLeft) == sfTrue) {
win->fps = 60;
sfRenderWindow_setFramerateLimit(win->window, win->fps);
}
if (win->mouse.x >= 1238 && win->mouse.y >= 477
&& win->mouse.x <= 1258 && win->mouse.y <= 497 &&
sfMouse_isButtonPressed(sfMouseLeft) == sfTrue) {
win->fps = 90;
sfRenderWindow_setFramerateLimit(win->window, win->fps);
}
}
void my_pause(object_l *menu, window_t *win)
{
draw(win->window, menu->menuparam->sprite);
if (sfKeyboard_isKeyPressed(sfKeyEscape) == sfTrue)
menu->mod = 0;
my_fps(win);
}<file_sep>/*
** EPITECH PROJECT, 2021
** utils
** File description:
** utils
*/
#include "rpg.h"
void draw(sfRenderWindow *window, sfSprite *sprite)
{
sfRenderWindow_drawSprite(window, sprite, NULL);
}<file_sep>/*
** EPITECH PROJECT, 2020
** mod_e
** File description:
** mod_e
*/
#include "../my_printf.h"
void print_mod_cape(double nb)
{
unsigned long long nbr = get_number(nb, nbr);
int *arr = get_arr(arr, nb, nbr);
if (nb < 0) {
nb *= -1;
my_putchar_p('-');
}
my_put_nbr_p(nbr / my_pow(10, arr[1]));
my_putchar_p('.');
arr[1]--;
for (int i = 1; i <= 6; i++, arr[1]--) {
my_put_nbr_p((nbr / my_pow(10, arr[1])) % 10);
}
if (nb > 1)
my_putstr_p("E+");
else if (nb < 1 && nb > 0)
my_putstr_p("E-");
if (arr[0] < 10)
my_putchar_p('0');
my_put_nbr_p(arr[0]);
}
<file_sep>/*
** EPITECH PROJECT, 2020
** print_hexa
** File description:
** print_hexa
*/
#include "../my_printf.h"
void print_hexa_lowcase(int nb)
{
if (nb >= 0 && nb <= 9)
my_put_nbr_p(nb);
if (nb == 10)
my_putchar_p('a');
if (nb == 11)
my_putchar_p('b');
if (nb == 12)
my_putchar_p('c');
if (nb == 13)
my_putchar_p('d');
if (nb == 14)
my_putchar_p('e');
if (nb == 15)
my_putchar_p('f');
}
void print_hexa_upcase(int nb)
{
if (nb >= 0 && nb <= 9)
my_put_nbr_p(nb);
if (nb == 10)
my_putchar_p('A');
if (nb == 11)
my_putchar_p('B');
if (nb == 12)
my_putchar_p('C');
if (nb == 13)
my_putchar_p('D');
if (nb == 14)
my_putchar_p('E');
if (nb == 15)
my_putchar_p('F');
}
void print_hexa(int nb, int mod)
{
int div = 0;
for (int times = 1, min; nb != 0; nb -= min) {
div = 0;
times = 1;
for (; my_pow(16, (div + 1)) <= nb; div++);
for (; (times + 1) * my_pow(16, div) <= nb; times++);
if (mod == 1)
print_hexa_lowcase(times);
if (mod == 2)
print_hexa_upcase(times);
min = times * my_pow(16, div);
}
for (; div != 0; div--)
my_putchar_p('0');
}
<file_sep>##
## EPITECH PROJECT, 2020
## CPool_Day10_2020
## File description:
## Makefile
##
SRC = my_compute_power_rec.c \
my_compute_square_root.c \
my_find_prime_sup.c \
my_getnbr.c \
my_getstr.c \
my_isneg.c \
my_is_prime.c \
my_putchar.c \
my_put_nbr.c \
my_putstr.c \
my_revstr.c \
my_showmem.c \
my_showstr.c \
my_sort_int_array.c \
my_strcapitalize.c \
my_strcat.c \
my_strcmp.c \
my_strcpy.c \
my_str_isalpha.c \
my_str_islower.c \
my_str_isnum.c \
my_str_is_printable.c \
my_str_isupper.c \
my_strlen.c \
my_strlowcase.c \
my_strncat.c \
my_strncmp.c \
my_strncpy.c \
my_strstr.c \
my_strupcase.c \
my_swap.c \
my_pow.c \
my_itoa.c \
open_map.c \
my_printf/my_printf.c \
my_printf/print_mod.c \
my_printf/add_files/my_putchar.c \
my_printf/add_files/my_putnbr.c \
my_printf/add_files/my_putstr.c \
my_printf/add_files/print_octal.c \
my_printf/add_files/my_revstr.c \
my_printf/add_files/my_getstr.c \
my_printf/add_files/print_binary.c \
my_printf/add_files/my_getnbr.c \
my_printf/add_files/print_hexa.c \
my_printf/add_files/print_mod_e.c \
my_printf/add_files/print_mod_cape.c \
my_printf/add_files/print_mod_f.c \
OBJ = $(SRC:.c=.o)
NAME = libmy.a
MY_H = my.h
BACK = ../
TO_INCLUDE = ../../include
TO_MY_H = ../../include/my.h
all: $(NAME)
$(NAME): $(OBJ)
ar rc -o $(NAME) $(OBJ)
cp $(NAME) $(BACK)
cp $(MY_H) $(TO_INCLUDE)
rm $(OBJ)
clean:
rm -f $(OBJ)
fclean: clean
rm -f $(NAME)
rm -f $(BACK)$(NAME)
rm -f $(TO_MY_H)
rm $(OBJ)
re: fclean all
.PHONY: clean fclean re<file_sep>/*
** EPITECH PROJECT, 2020
** getstr
** File description:
** getstr
*/
#include <stdlib.h>
int my_strlen(char *str);
int my_intlen(int nb)
{
int i = 0;
if (nb > 0)
for (; nb > 1; i++)
nb /= 10;
if (nb < 0)
for (; nb < -1; i++)
nb /= 10;
if (nb = 0)
return 1;
i++;
return i;
}
int my_pow(int nb, int pow)
{
int result = nb;
if (pow == 1)
return result;
if (pow == 0)
return 1;
for (int i = 1; i < pow; i++)
result *= nb;
return result;
}
char *my_getstr(int nb)
{
int t = 0;
char *str = malloc(sizeof(char) * (my_intlen(nb) + 1));
if (nb < 0) {
nb *= -1;
str[t] = '-';
t++;
}
for (int i = my_intlen(nb); i > 0; i--, t++)
str[t] = ((nb / my_pow(10, (i - 1)) % 10) + '0');
return str;
}
<file_sep>/*
** EPITECH PROJECT, 2021
** my rpg
** File description:
** create map
*/
#include "rpg.h"
sfSprite **create_chest(char *path)
{
sfSprite **sprites = malloc(sizeof(sfSprite *) * 2);
sfTexture *texture = sfTexture_createFromFile(path , NULL);
sfIntRect rect = {0, 0, 82, 88};
for (int i = 0; i < 2; ++i) {
sprites[i] = sfSprite_create();
sfSprite_setTexture(sprites[i], texture, sfTrue);
sfSprite_setTextureRect(sprites[i], rect);
rect.left += 82;
}
return sprites;
}
sfSprite **create_teleport(char *path)
{
sfSprite **sprites = malloc(sizeof(sfSprite *) * 6);
sfTexture *texture = sfTexture_createFromFile(path , NULL);
sfIntRect rect = {0, 0, 256, 128};
for (int i = 0; i < 5; ++i) {
sprites[i] = sfSprite_create();
sfSprite_setTexture(sprites[i], texture, sfTrue);
sfSprite_setTextureRect(sprites[i], rect);
rect.top += 128;
}
sprites[5] = NULL;
return sprites;
}
sfSprite **create_map(char *path)
{
sfSprite **sprites = malloc(sizeof(sfSprite *) * 16);
sfTexture *texture = sfTexture_createFromFile(path , NULL);
sfIntRect rect = {0, 0, 96, 96};
for (int i = 0; i < 16; ++i) {
sprites[i] = sfSprite_create();
sfSprite_setTexture(sprites[i], texture, sfTrue);
sfSprite_setTextureRect(sprites[i], rect);
rect.left += 96;
if (rect.left == 768) {
rect.left = 0;
rect.top += 96;
}
}
return sprites;
}<file_sep>/*
** EPITECH PROJECT, 2020
** get_nbr
** File description:
** get_nbr
*/
int get_start(char const *str)
{
int i = 0;
while (str[i] != '-' && (str[i] < '0' || str[i] > '9'))
i++;
return i;
}
int my_getnbr(char const *str)
{
int n = 0;
int k = 0;
int i = get_start(str);
if (str[i] == '-') {
k = 1;
i++;
}
while (str[i] != '\0' && str[i] <= '9' && str[i] >= '0') {
n = n + (str[i] - '0');
n *= 10;
i++;
}
n /= 10;
if (k == 1)
n *= -1;
return (n);
}
<file_sep>/*
** EPITECH PROJECT, 2021
** inv utils
** File description:
** inv utils
*/
#include "rpg.h"
player_t *put_rect(player_t *player, int nb)
{
player->weapon = player->inv->items[nb];
player->inv->hotrect->pos.x = (float) player->inv->slot_pos[nb][0] + 2;
player->inv->hotrect->pos.y = (float) player->inv->slot_pos[nb][1] - 7;
return player;
}<file_sep>/*
** EPITECH PROJECT, 2021
** chest_hb
** File description:
** chest_hb
*/
#include "rpg.h"
int open_chest(window_t *win, level_t *lvl, player_t *player, int i)
{
if (player->object->pos.x <= lvl->chests[lvl->lvl][i]->pos.x + 157
&& player->object->pos.x + 100 >= lvl->chests[lvl->lvl][i]->pos.x + 50
&& player->object->pos.y <= lvl->chests[lvl->lvl][i]->pos.y + 100
&& player->object->pos.y + 134 >= lvl->chests[lvl->lvl][i]->pos.y
&& lvl->chests[lvl->lvl][i]->is_closed == 0) {
draw(win->window, player->press_space->sprite);
if (sfKeyboard_isKeyPressed(sfKeySpace) == sfTrue)
return 1;
}
return 0;
}<file_sep>/*
** EPITECH PROJECT, 2021
** lvl_transition
** File description:
** lvl_transition
*/
#include "rpg.h"
static window_t *start_transition(window_t *win, level_t *lvl, pbl_t *game)
{
if (win->l_state == 1)
win->transcolor += 5;
if (win->transcolor == 255 && win->l_state == 1) {
++lvl->lvl;
if (lvl->maps[lvl->lvl] == NULL) {
launch_transition(win, 4);
transition(win);
return win;
}
win->map_pos = lvl->spawns[lvl->lvl];
lvl->ennemy[lvl->lvl] = create_ennemies(lvl, win->l_mod,
(int) lvl->spawns[lvl->lvl].x, (int) lvl->spawns[lvl->lvl].y);
win->l_state = 2;
} else if (win->l_state == 2)
win->transcolor -= 10;
if (win->transcolor <= 0 && win->l_state == 2) {
win->l_state = 0;
win->transcolor = 0;
}
return win;
}
void launch_lvl_transition(window_t *win, level_t *lvl, player_t *player)
{
sfVector2f pos = win->map_pos;
if (pos.x + 30 - 943 < lvl->warps[lvl->lvl].x + 96
&& pos.x + 70 - 943 > lvl->warps[lvl->lvl].x
&& pos.y - 430 < lvl->warps[lvl->lvl].y + 96
&& pos.y - 450 > lvl->warps[lvl->lvl].y) {
sfSound_play(win->sound->list[11]);
if (lvl->lvl < 6)
win->l_mod = 15 * (lvl->lvl + 1);
else
win->l_mod = (15 * (lvl->lvl + 1)) / 2;
win->l_state = 1;
}
}
void lvl_transition(window_t *win, level_t *lvl, player_t *player, pbl_t *game)
{
launch_lvl_transition(win, lvl, player);
win = start_transition(win, lvl, game);
sfSprite_setColor(win->trans->sprite,
sfColor_fromRGBA(0, 0, 0, win->transcolor));
draw(win->window, win->trans->sprite);
}<file_sep>/*
** EPITECH PROJECT, 2020
** B-MUL-200-PAR-2-1-myrpg-julien.de-waele
** File description:
** sound.c
*/
#include "rpg.h"
sfSound *create_sound(char *path)
{
sfSound *sound = sfSound_create();
sfSoundBuffer *sbuff = sfSoundBuffer_createFromFile(path);
sfSound_setBuffer(sound, sbuff);
sfSound_setLoop(sound, sfFalse);
return sound;
}
sfSound **init_sound(void)
{
sfSound **list = malloc(sizeof(sfSound *) * 13);
list[0] = create_sound("./image/sound/Absorb2.ogg");
list[1] = create_sound("./image/sound/blaster_14.ogg");
list[2] = create_sound("./image/sound/Cold10.ogg");
list[3] = create_sound("./image/sound/Collapse4.ogg");
list[4] = create_sound("./image/sound/Damage3.ogg");
list[5] = create_sound("./image/sound/Decision1.ogg");
list[6] = create_sound("./image/sound/Equip1.ogg");
list[7] = create_sound("./image/sound/Item3.ogg");
list[8] = create_sound("./image/sound/Open1.ogg");
list[9] = create_sound("./image/sound/Powerup.ogg");
list[10] = create_sound("./image/sound/Recovery8.ogg");
list[11] = create_sound("./image/sound/Teleport_DBZ_Sound_Effect.ogg");
list[12] = create_sound("./image/sound/Scream-02.ogg");
return list;
}
sound_t *init_audio(void)
{
sound_t *audio = malloc(sizeof(sound_t));
audio->music = sfMusic_createFromFile("./image/sound/mainsong.ogg");
sfMusic_setLoop(audio->music, sfTrue);
audio->list = init_sound();
return audio;
}<file_sep>/*
** EPITECH PROJECT, 2021
** create_inv
** File description:
** create_inv
*/
#include "rpg.h"
rect_t *create_inv_rect(int a)
{
rect_t *obj = malloc(sizeof(rect_t));
obj->rect = sfRectangleShape_create();
sfColor outcolor = sfColor_fromRGBA(8, 98, 175, a);
sfColor incolor = sfColor_fromRGBA(8, 98, 175, a);
obj->size.x = 74;
obj->size.y = 74;
sfRectangleShape_setSize(obj->rect, obj->size);
sfRectangleShape_setOutlineColor(obj->rect, outcolor);
sfRectangleShape_setFillColor(obj->rect, incolor);
sfRectangleShape_setOutlineThickness(obj->rect, 1);
return obj;
}
rect_t *create_minimap_rect(void)
{
rect_t *obj = malloc(sizeof(rect_t));
obj->rect = sfRectangleShape_create();
sfColor outcolor = sfColor_fromRGBA(100, 100, 100, 200);
obj->size.x = 5;
obj->size.y = 5;
sfRectangleShape_setSize(obj->rect, obj->size);
sfRectangleShape_setOutlineColor(obj->rect, outcolor);
sfRectangleShape_setFillColor(obj->rect, outcolor);
return obj;
}
inventory_t *create_inventory2(inventory_t *inv, sfVector2f pos)
{
inv->display = 0;
inv->is_swapping = 0;
inv->hotrect->pos.x = 1776.0;
inv->hotrect->pos.y = 313.0;
inv->s_index = 21;
sfRectangleShape_setPosition(inv->hotrect->rect, inv->hotrect->pos);
inv->stat_b = create_object("image/stats.png", 1300, 300);
inv->trash = create_object("image/trash.png", 1779, 860);
inv->stat_txt = create_text("yo", 0, 0, 45);
inv->items[24] = malloc(sizeof(weapon_t));
inv->mini_rect = create_minimap_rect();
return inv;
}
inventory_t *create_inventory(inventory_t *inv, sfVector2f pos)
{
inv = malloc(sizeof(inventory_t));
inv->object = create_object("image/inv.png", 1300, 600);
inv->hotbar = create_object("image/hotb.png", 1762, 300);
sfColor grey = {155, 155, 155, 255};
sfSprite_setColor(inv->object->sprite, grey);
inv->items = malloc(sizeof(weapon_t *) * 25);
inv->slot_pos = malloc(sizeof(int *) * 25);
for (int i = 0; i < 25; i++) {
inv->items[i] = malloc(sizeof(weapon_t));
inv->slot_pos[i] = malloc(sizeof(int) * 2);
inv->slot_pos[i][0] = 0;
inv->slot_pos[i][1] = 0;
inv->items[i] = NULL;
}
inv->items[21] = malloc(sizeof(weapon_t));
inv->stock = NULL;
inv->rect = create_inv_rect(100);
inv->hotrect = create_inv_rect(50);
inv = create_inventory2(inv, pos);
return inv;
}<file_sep>/*
** EPITECH PROJECT, 2021
** main
** File description:
** main
*/
#include "rpg.h"
void events(window_t *win)
{
while (sfRenderWindow_pollEvent(win->window, &win->event)) {
if (win->event.type == sfEvtClosed)
sfRenderWindow_close(win->window);
}
}
pbl_t *init_game(void)
{
pbl_t *game = malloc(sizeof(pbl_t));
game->menu = create_mm_sprites();
game->player = create_player();
game->ground = create_map("./image/res_map/grounds.png");
game->tp = create_teleport("./image/teleport.png");
game->tp_clock = sfClock_create();
game->lvl = create_level();
game->lose = init_lose();
return game;
}
int main(void)
{
window_t *window = create_window();
pbl_t *game = init_game();
srand(time(NULL));
window->map_pos = game->lvl->spawns[game->lvl->lvl];
while (sfRenderWindow_isOpen(window->window)) {
sfRenderWindow_clear(window->window, sfBlack);
events(window);
mode(game, window);
sfRenderWindow_display(window->window);
}
sfMusic_destroy(window->sound->music);
sfRenderWindow_destroy(window->window);
return 0;
}<file_sep>/*
** EPITECH PROJECT, 2021
** create_level
** File description:
** create_level
*/
#include "rpg.h"
static int *take_size(char *buffer)
{
int *pos = malloc(sizeof(int) * 2);
buffer[my_strlen(buffer) - 1] = '\0';
for (int k = 0; buffer[k] != '\0'; ++k)
if (buffer[k] == '*') {
pos[0] = my_getnbr(&buffer[k + 1]);
buffer[k] = '\0';
pos[1] = my_getnbr(buffer);
}
return pos;
}
static int place_map(char **map, char *buffer, int i, int pos)
{
for (int j = 0; buffer[j] != '\0'; ++j) {
if (buffer[j] == '\n')
break;
else
map[i][j] = buffer[j];
}
map[i][pos] = '\0';
return (i + 1);
}
static char **createmapfromfile(char *path)
{
size_t len;
FILE *fd = fopen(path, "r");
char *buf = NULL;
int *pos = NULL;
char **map = NULL;
getline(&buf, &len, fd);
pos = take_size(buf);
map = malloc(sizeof(char *) * (pos[0] + 1));
for (int i = 0; i < pos[0]; ++i)
map[i] = malloc(sizeof(char) * (pos[1] + 1));
for (int k = 0, i = 0; k < pos[0]; ++k) {
getline(&buf, &len, fd);
i = place_map(map, buf, i, pos[1]);
}
map[pos[0]] = NULL;
free(buf);
free(pos);
fclose(fd);
return (map);
}
static level_t *map_info(level_t *lvl, char *path, int i)
{
lvl->maps[i] = createmapfromfile(path);
for (int line = 0; lvl->maps[i][line] != NULL; ++line)
for (int y = 0; lvl->maps[i][line][y] != '\0'; ++y) {
if (lvl->maps[i][line][y] == '3') {
lvl->spawns[i].x = (float) (y * -96 + 943);
lvl->spawns[i].y = (float) (line * -96 + 480);
} else if (lvl->maps[i][line][y] == '0') {
lvl->warps[i].x = (float) (y * -96);
lvl->warps[i].y = (float) (line * -96);
}
}
return lvl;
}
level_t *create_level(void)
{
level_t *lvl = create_level_memory();
lvl = map_info(lvl, "src/maps/level_start.txt", 0);
lvl = map_info(lvl, "src/maps/level1.txt", 1);
lvl = map_info(lvl, "src/maps/level2.txt", 2);
lvl = map_info(lvl, "src/maps/level3.txt", 3);
lvl = map_info(lvl, "src/maps/level4.txt", 4);
lvl = map_info(lvl, "src/maps/level5.txt", 5);
lvl = map_info(lvl, "src/maps/level6.txt", 6);
lvl = map_info(lvl, "src/maps/level7.txt", 7);
lvl = map_info(lvl, "src/maps/level8.txt", 8);
lvl = map_info(lvl, "src/maps/level9.txt", 9);
lvl = map_info(lvl, "src/maps/level10.txt", 10);
lvl->ennemy = create_all_ennemies(lvl);
lvl->chests = create_all_chests(lvl);
return lvl;
}<file_sep>/*
** EPITECH PROJECT, 2021
** minimap
** File description:
** minimap
*/
#include "rpg.h"
inventory_t *change_mc(window_t *win, level_t *lvl, inventory_t *inv, int c)
{
sfColor outcolor = sfColor_fromRGBA(100, 100, 100, 200);
if (c == ' ')
outcolor = sfColor_fromRGBA(100, 100, 100, 200);
if (c == '3')
outcolor = sfColor_fromRGBA(100, 10, 100, 200);
if (c != ' ' && c != '3')
outcolor = sfColor_fromRGBA(200, 200, 200, 200);
sfRectangleShape_setOutlineColor(inv->mini_rect->rect, outcolor);
sfRectangleShape_setFillColor(inv->mini_rect->rect, outcolor);
return inv;
}
inventory_t *change_to_red(inventory_t *inv)
{
sfColor outcolor = sfColor_fromRGBA(200, 30, 30, 200);
sfRectangleShape_setOutlineColor(inv->mini_rect->rect, outcolor);
sfRectangleShape_setFillColor(inv->mini_rect->rect, outcolor);
return inv;
}
void draw_minimap(window_t *win, level_t *lvl, player_t *player)
{
int x = (win->map_pos.x * -1 + 1010) / 96;
int y = (win->map_pos.y * -1 + 560) / 96;
for (int i = 0; lvl->maps[lvl->lvl][i] != NULL; ++i)
for (int t = 0; lvl->maps[lvl->lvl][i][t] != '\0'; ++t) {
player->inv->mini_rect->pos.x = t * 5 + 5;
player->inv->mini_rect->pos.y = i * 5 + 5;
sfRectangleShape_setPosition(player->inv->mini_rect->rect,
player->inv->mini_rect->pos);
player->inv = change_mc(win, lvl, player->inv,
lvl->maps[lvl->lvl][i][t]);
if (x == t && y == i)
player->inv = change_to_red(player->inv);
sfRenderWindow_drawRectangleShape(win->window,
player->inv->mini_rect->rect, NULL);
}
}<file_sep>/*
** EPITECH PROJECT, 2020
** B-MUL-200-PAR-2-1-myrpg-julien.de-waele
** File description:
** allocate_level.c
*/
#include "rpg.h"
level_t *create_level_memory(void)
{
level_t *lvl = malloc(sizeof(level_t));
lvl->lvl = 0;
lvl->spawns = malloc(sizeof(sfVector2f) * 12);
lvl->warps = malloc(sizeof(sfVector2f) * 12);
lvl->maps = malloc(sizeof(char **) * 12);
lvl->maps[11] = NULL;
return lvl;
}<file_sep>/*
** EPITECH PROJECT, 2021
** inventory
** File description:
** inventory
*/
#include "rpg.h"
player_t *update_slots_pos(player_t *player)
{
sfVector2f pos = {1305, 612};
for (int i = 0, t = 0, k = 0; i < 21; i++, t++) {
if (t == 7 || t == 14) {
t = 0;
k++;
}
player->inv->slot_pos[i][0] = pos.x + t * 79.5;
player->inv->slot_pos[i][1] = pos.y + k * 79.5;
}
player->inv->slot_pos[21][0] = 1774;
player->inv->slot_pos[21][1] = 320;
player->inv->slot_pos[22][0] = 1774;
player->inv->slot_pos[22][1] = 400;
player->inv->slot_pos[23][0] = 1774;
player->inv->slot_pos[23][1] = 480;
player->inv->slot_pos[24][0] = 1784;
player->inv->slot_pos[24][1] = 873;
return player;
}
int check_mouse_on_slot(player_t *player, window_t *win, int i)
{
if (win->mouse.x >= player->inv->slot_pos[i][0]
&& win->mouse.x <= player->inv->slot_pos[i][0] + 79
&& win->mouse.y >= player->inv->slot_pos[i][1]
&& win->mouse.y <= player->inv->slot_pos[i][1] + 78)
return 1;
return 0;
}
player_t *reset_inv(player_t *player, window_t *win)
{
player = update_slots_pos(player);
player = switch_weapons(player->inv, player, win);
for (int i = 0; i < 25; i++)
if (check_mouse_on_slot(player, win, i) == 1) {
if (player->inv->items[i] != NULL
&& sfMouse_isButtonPressed(sfMouseLeft) == sfTrue) {
player->inv->is_swapping = 1;
player->inv->index = i;
}
if (player->inv->items[i] != NULL)
player->inv->s_index = i;
player->inv->s_index2 = i;
player->inv->rect->pos.x = (float) player->inv->slot_pos[i][0] + 2;
player->inv->rect->pos.y = (float) player->inv->slot_pos[i][1] - 7;
}
sfRectangleShape_setPosition(player->inv->rect->rect,
player->inv->rect->pos);
return player;
}
void draw_inv(player_t *player, window_t *win)
{
draw(win->window, player->inv->object->sprite);
draw(win->window, player->inv->stat_b->sprite);
draw(win->window, player->inv->trash->sprite);
print_stats(player->inv, win);
draw_inv_weapons(player->inv, win);
sfRenderWindow_drawRectangleShape(win->window,
player->inv->rect->rect, NULL);
display_pstart(win, player);
}
void inventory_display(player_t *player, window_t *win)
{
if (sfKeyboard_isKeyPressed(sfKeyI) == sfTrue
&& player->inv->display == 0 && win->quest->mod == 3) {
player->inv->display = 1;
player->inv->rect->pos.x = (float) player->inv->slot_pos[0][0] + 2;
player->inv->rect->pos.y = (float) player->inv->slot_pos[0][1] - 7;
sfRectangleShape_setPosition(player->inv->rect->rect,
player->inv->rect->pos);
sfSound_play(win->sound->list[5]);
}
draw_hot_weapons(player->inv, win);
if (player->inv->display == 1) {
draw_inv(player, win);
player->inv = swap_items(player->inv, win);
}
player = reset_inv(player, win);
if (sfKeyboard_isKeyPressed(sfKeyEscape) == sfTrue
&& player->inv->display == 1)
player->inv->display = 0;
if (sfKeyboard_isKeyPressed(sfKeyM) == sfTrue)
player->inv = generate_weapon(player->inv);
}<file_sep>/*
** EPITECH PROJECT, 2021
** shoot
** File description:
** shoot
*/
#include "rpg.h"
player_t *bullet_speed(player_t *player)
{
sfTime time = sfClock_getElapsedTime(player->weapon->clock);
if ((time.microseconds / (player->weapon->ms * 1000.0)) > 1) {
player->weapon->canshoot = 1;
sfClock_restart(player->weapon->clock);
}
return player;
}
player_t *get_bullet_dir(player_t *player, window_t *win)
{
if (win->mouse.x < 990 && win->mouse.y >= 360 && win->mouse.y <= 720)
player->shootdir = 1;
if (win->mouse.x > 990 && win->mouse.y >= 360 && win->mouse.y <= 720)
player->shootdir = 2;
if (win->mouse.y < 450 && win->mouse.x >= 640 && win->mouse.x <= 1280)
player->shootdir = 3;
if (win->mouse.y > 630 && win->mouse.x >= 640 && win->mouse.x <= 1280)
player->shootdir = 4;
return bullet_speed(player);
}
void move_bullets(player_t *player, int i)
{
if (player->shoot[i]->direction == 1)
player->shoot[i]->pos.x -= 25;
if (player->shoot[i]->direction == 2)
player->shoot[i]->pos.x += 25;
if (player->shoot[i]->direction == 3)
player->shoot[i]->pos.y -= 25;
if (player->shoot[i]->direction == 4)
player->shoot[i]->pos.y += 25;
animat_bullet(player->shoot[i], player->shoot[i]->anim,
player->shoot[i]->anim * 6, 130);
destroy_bullet(player, i);
}
player_t *get_bullet(player_t *player, int i)
{
sfVector2f pos = player->object->pos;
if (player->shootdir == 1) {
player->shoot[i] = create_bullet("image/l_bul.png", player, 960, 470);
player->shoot[i] = init_bullet_rect(player->shoot[i], 70, 55, 55);
player->shoot[i]->anim = 70;
} else if (player->shootdir == 2) {
player->shoot[i] = create_bullet("image/l_bul.png", player, 955, 470);
player->shoot[i] = init_bullet_rect(player->shoot[i], 70, 55, 0);
player->shoot[i]->anim = 70;
}
if (player->shootdir == 3) {
player->shoot[i] = create_bullet("image/l_bul.png", player, 965, 455);
player->shoot[i] = init_bullet_rect(player->shoot[i], 55, 70, 110);
player->shoot[i]->anim = 55;
} else if (player->shootdir == 4) {
player->shoot[i] = create_bullet("image/l_bul.png", player, 963, 470);
player->shoot[i] = init_bullet_rect(player->shoot[i], 55, 70, 180);
player->shoot[i]->anim = 55;
}
return player;
}
void shoot(player_t *player, window_t *window)
{
player = get_bullet_dir(player, window);
if (sfMouse_isButtonPressed(sfMouseLeft) == sfTrue
&& player->weapon->canshoot == 1 && player->inv->display != 1) {
sfSound_play(window->sound->list[1]);
for (int i = 0; i < 10; i++)
if (player->shoot[i] == NULL && window->quest->mod == 3) {
player->weapon->canshoot = 0;
player = get_bullet(player, i);
break;
}
}
for (int i = 0; i < 10; i++)
if (player->shoot[i] != NULL) {
move_bullets(player, i);
if (player->shoot[i] != NULL) {
sfSprite_setPosition(player->shoot[i]->sprite,
player->shoot[i]->pos);
draw(window->window, player->shoot[i]->sprite);
}
}
}<file_sep>##
## EPITECH PROJECT, 2020
## issam ch
## File description:
## makefile
##
SRC = src/main.c \
src/menus/transition.c \
src/menus/main_menu.c \
src/menus/lose.c \
src/menus/create_main_menu.c \
src/menus/quest.c \
src/menus/my_pause.c \
src/menus/control_sound.c \
src/menus/my_info.c \
src/create/create_object.c \
src/create/create_window.c \
src/create/create_text.c \
src/player/create_player.c \
src/player/player.c \
src/player/player2.c \
src/player/bullets/shoot.c \
src/player/bullets/bullet_utils.c \
src/player/inv/create_inv.c \
src/player/inv/inventory.c \
src/player/inv/inv_utils.c \
src/player/inv/create_wtype.c \
src/player/inv/stats.c \
src/player/inv/minimap.c \
src/player/collisions.c \
src/player/weapons/weapons.c \
src/player/weapons/draw_weapons.c \
src/player/pstats.c \
src/player/display_pstat.c \
src/player/orb.c \
src/ennemies/create_ennemies.c \
src/ennemies/ennemies.c \
src/ennemies/ennemies_hb.c \
src/level/create_levels.c \
src/level/lvl_transition.c \
src/level/allocate_levels.c \
src/chests/init_chests.c \
src/chests/chest_hb.c \
src/audio/sound.c \
src/mode.c \
src/utils.c \
src/create/create_map.c \
src/draw_ground.c \
OBJ = $(SRC:.c=.o)
NAME = my_rpg
CPPFLAGS = -I./include -I./lib/my
LIB = -L./lib/my -lmy
CFLAGS = -g3
CSFMLFLAGS = -l csfml-graphics -l csfml-window -l csfml-system -l csfml-audio
LIB_PTH = lib/my/
DOTE_A = lib/my/libmy.a lib/libmy.a
MY_H = include/my.h
all: $(NAME)
$(NAME): $(OBJ)
make -s -C $(LIB_PTH)
gcc -o $(NAME) $(OBJ) $(CSFMLFLAGS) $(LIB) $(CPPFLAGS)
rm $(OBJ)
clean:
rm -f *.c~
rm -f Makefile~
rm -f $(OBJ)
fclean: clean
rm -f $(NAME)
rm -f $(DOTE_A)
rm -f $(MY_H)
re: fclean all
.PHONY: re fclean clean all<file_sep>/*
** EPITECH PROJECT, 2020
** rev_list.c
** File description:
** rev_lis
*/
<file_sep>/*
** EPITECH PROJECT, 2020
** B-MUL-200-PAR-2-1-myrpg-julien.de-waele
** File description:
** lose.c
*/
#include "rpg.h"
lose_t *init_lose(void)
{
lose_t *lose = malloc(sizeof(lose_t));
sfVector2f pos = {50.0, 67.0};
lose->game_over = create_object("image/gameover.png", 0, 0);
lose->game_over = init_rect(lose->game_over, 0, 1080, 0);
lose->skin = create_object("image/lose_skin.png", 960, -300);
lose->exit = create_object("image/exitgameover.png", 138, 870);
lose->home = create_object("image/restartgameover.png", 1403, 878);
sfSprite_setColor(lose->exit->sprite,
sfColor_fromRGBA(255, 255, 255, 0));
sfSprite_setColor(lose->home->sprite,
sfColor_fromRGBA(255, 255, 255, 0));
sfSprite_setOrigin(lose->skin->sprite, pos);
return lose;
}
void exit_or_restart(window_t *win, lose_t *lose, int exit_home)
{
if (exit_home >= 254) {
if (win->mouse.x >= lose->exit->pos.x
&& win->mouse.x <= lose->exit->pos.x + 206
&& win->mouse.y >= lose->exit->pos.y
&& win->mouse.y <= lose->exit->pos.y + 70
&& sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
sfRenderWindow_close(win->window);
if (win->mouse.x >= lose->home->pos.x
&& win->mouse.x <= lose->home->pos.x + 349
&& win->mouse.y >= lose->home->pos.y
&& win->mouse.y <= lose->home->pos.y + 59
&& sfMouse_isButtonPressed(sfMouseLeft) == sfTrue) {
sfRenderWindow_close(win->window);
main();
}
}
}
void draw_lose(window_t *win, lose_t *lose)
{
sfSprite_setPosition(lose->skin->sprite, lose->skin->pos);
draw(win->window, lose->game_over->sprite);
draw(win->window, lose->skin->sprite);
draw(win->window, lose->exit->sprite);
draw(win->window, lose->home->sprite);
}
void change_fade_color(window_t *win, lose_t *lose, int exit_home)
{
sfSprite_setColor(lose->exit->sprite,
sfColor_fromRGBA(255, 255, 255, exit_home));
sfSprite_setColor(lose->home->sprite,
sfColor_fromRGBA(255, 255, 255, exit_home));
}
void do_lose(window_t *win, lose_t *lose)
{
static int width = -200;
static int exit_home = -400;
if (width <= 1920)
width += 10;
if (width >= 0) {
lose->game_over->rect.width = width;
sfSprite_setTextureRect(lose->game_over->sprite, lose->game_over->rect);
}
if (lose->skin->pos.y <= 1200) {
lose->skin->pos.y += 7;
sfSprite_rotate(lose->skin->sprite, 5.0);
}
if (exit_home < 254)
exit_home += 3;
if (exit_home >= 0)
change_fade_color(win, lose, exit_home);
exit_or_restart(win, lose, exit_home);
draw_lose(win, lose);
transition(win);
}<file_sep>/*
** EPITECH PROJECT, 2021
** controle_sound.c
** File description:
** controle sound
*/
#include "rpg.h"
void controle_menu_sound(object_l *menu, window_t *win)
{
win->sound_m->rect.width = 766 + (3.85 * win->snd);
sfSprite_setTextureRect(win->sound_m->sprite, win->sound_m->rect);
if (win->mouse.x >= 646 && win->mouse.x <= 691
&& win->mouse.y >= 683 && win->mouse.y <= 697
&& win->snd > 0 && sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
win->snd--;
if (win->mouse.x >= 1227 && win->mouse.x <= 1270
&& win->mouse.y >= 670 && win->mouse.y <= 711
&& win->snd < 100 && sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
win->snd++;
draw(win->window, win->sound_m->sprite);
}
void controle_game_sound(object_l *menu, window_t *win)
{
win->sound_g->rect.width = 780 + (3.66 * win->snd);
sfSprite_setTextureRect(win->sound_g->sprite, win->sound_g->rect);
if (win->mouse.x >= 694 && win->mouse.x <= 718
&& win->mouse.y >= 425 && win->mouse.y <= 439
&& win->snd > 0 && sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
win->snd--;
if (win->mouse.x >= 1205 && win->mouse.x <= 1235
&& win->mouse.y >= 416 && win->mouse.y <= 452
&& win->snd < 100 && sfMouse_isButtonPressed(sfMouseLeft) == sfTrue)
win->snd++;
draw(win->window, win->sound_g->sprite);
}<file_sep>/*
** EPITECH PROJECT, 2020
** my_putnbr
** File description:
** my_putnbr
*/
#include "../my_printf.h"
void my_put_nbr_p(long nb)
{
int md;
if (nb < 0) {
my_putchar_p('-');
nb = nb * (-1);
}
if (nb >= 0) {
if (nb >= 10) {
md = nb % 10;
nb = (nb - md) /10;
my_put_nbr_p(nb);
my_putchar_p(48 + md);
}
else
my_putchar_p(48 + nb %10);
}
}
<file_sep>/*
** EPITECH PROJECT, 2020
** my_pow
** File description:
** my_pow
*/
int my_pow(int nb, int pow)
{
int result = nb;
if (pow == 1)
return result;
if (pow == 0)
return 1;
for (int i = 1; i < pow; i++)
result *= nb;
return result;
}
<file_sep>/*
** EPITECH PROJECT, 2021
** weapon type
** File description:
** weapon type
*/
#include "rpg.h"
weapon_t *create_glock(weapon_t *item, inventory_t *inv, int i)
{
item->dmg = (rand() % 16) + 12;
item->ms = (rand() % 201) + 900;
item->object = create_object("image/glock.png",
inv->slot_pos[i][1], inv->slot_pos[i][0]);
item->clock = sfClock_create();
inv->items[i]->canshoot = 1;
inv->items[i]->index = i;
return item;
}
weapon_t *create_rifle(weapon_t *item, inventory_t *inv, int i)
{
item->dmg = (rand() % 11) + 10;
item->ms = (rand() % 301) + 400;
item->object = create_object("image/rifle.png",
inv->slot_pos[i][1], inv->slot_pos[i][0]);
item->clock = sfClock_create();
inv->items[i]->canshoot = 1;
inv->items[i]->index = i;
return item;
}
weapon_t *create_snipe(weapon_t *item, inventory_t *inv, int i)
{
item->dmg = (rand() % 21) + 20;
item->ms = (rand() % 301) + 1300;
item->object = create_object("image/snipe.png",
inv->slot_pos[i][1], inv->slot_pos[i][0]);
item->clock = sfClock_create();
inv->items[i]->canshoot = 1;
inv->items[i]->index = i;
return item;
}<file_sep>/*
** EPITECH PROJECT, 2021
** pstats
** File description:
** pstats
*/
#include "rpg.h"
rect_t *create_pstat_rect(void)
{
rect_t *obj = malloc(sizeof(rect_t));
obj->rect = sfRectangleShape_create();
sfColor outcolor = sfColor_fromRGBA(0, 0, 0, 255);
sfColor incolor = sfColor_fromRGBA(0, 0, 0, 0);
obj->size.x = 300;
obj->size.y = 30;
sfRectangleShape_setSize(obj->rect, obj->size);
sfRectangleShape_setOutlineColor(obj->rect, outcolor);
sfRectangleShape_setFillColor(obj->rect, incolor);
sfRectangleShape_setOutlineThickness(obj->rect, 1);
obj->pos.x = 1550;
return obj;
}
void draw_lifebarre(pstats_t *stats, window_t *win)
{
stats->rect->pos.y = 20;
if (stats->life <= 0)
stats->life = 0;
sfRectangleShape_setPosition(stats->rect->rect, stats->rect->pos);
stats->rect->size.x = (300 * stats->life) / stats->max_life;
sfColor outcolor = sfColor_fromRGBA(0, 0, 0, 0);
sfColor incolor = sfColor_fromRGBA(139, 0, 0, 255);
sfRectangleShape_setSize(stats->rect->rect, stats->rect->size);
sfRectangleShape_setOutlineColor(stats->rect->rect, outcolor);
sfRectangleShape_setFillColor(stats->rect->rect, incolor);
sfRectangleShape_setOutlineThickness(stats->rect->rect, 1);
sfRenderWindow_drawRectangleShape(win->window, stats->rect->rect, NULL);
outcolor = sfColor_fromRGBA(0, 0, 0, 255);
incolor = sfColor_fromRGBA(0, 0, 0, 0);
stats->rect->size.x = 300;
sfRectangleShape_setSize(stats->rect->rect, stats->rect->size);
sfRectangleShape_setOutlineColor(stats->rect->rect, outcolor);
sfRectangleShape_setFillColor(stats->rect->rect, incolor);
sfRectangleShape_setOutlineThickness(stats->rect->rect, 3);
sfRenderWindow_drawRectangleShape(win->window, stats->rect->rect, NULL);
}
void draw_xp(pstats_t *stats, window_t *win)
{
stats->dmg = stats->lvl;
stats->armor = stats->lvl / 3;
stats->rect->pos.y = 70;
sfRectangleShape_setPosition(stats->rect->rect, stats->rect->pos);
stats->rect->size.x = (300 * stats->xp) / (stats->lvl * 2);
sfColor outcolor = sfColor_fromRGBA(0, 0, 0, 0);
sfColor incolor = sfColor_fromRGBA(0, 128, 0, 255);
sfRectangleShape_setSize(stats->rect->rect, stats->rect->size);
sfRectangleShape_setOutlineColor(stats->rect->rect, outcolor);
sfRectangleShape_setFillColor(stats->rect->rect, incolor);
sfRectangleShape_setOutlineThickness(stats->rect->rect, 1);
sfRenderWindow_drawRectangleShape(win->window, stats->rect->rect, NULL);
outcolor = sfColor_fromRGBA(0, 0, 0, 255);
incolor = sfColor_fromRGBA(0, 0, 0, 0);
stats->rect->size.x = 300;
sfRectangleShape_setSize(stats->rect->rect, stats->rect->size);
sfRectangleShape_setOutlineColor(stats->rect->rect, outcolor);
sfRectangleShape_setFillColor(stats->rect->rect, incolor);
sfRectangleShape_setOutlineThickness(stats->rect->rect, 3);
sfRenderWindow_drawRectangleShape(win->window, stats->rect->rect, NULL);
}
pstats_t *init_pstats(void)
{
pstats_t *stat = malloc(sizeof(pstats_t));
stat->lvl = 1;
stat->max_life = 90 + 10 * stat->lvl;
stat->life = stat->max_life;
stat->lvl_up = create_object("image/lvl_up.png", 540, 150);
stat->lvl_up = init_rect(stat->lvl_up, 900, 339, 0);
stat->rect = create_pstat_rect();
stat->lvl_up->clock = sfClock_create();
stat->dmg = 5 * stat->lvl;
stat->armor = 5 * stat->lvl;
stat->launch_lvlup = 0;
stat->xp = 0;
return stat;
}
pstats_t *update_stats(window_t *win, pstats_t *stats)
{
if (stats->xp == stats->lvl * 2) {
sfSound_play(win->sound->list[3]);
stats->launch_lvlup = 1;
stats->xp = 0;
stats->lvl++;
stats->max_life = 90 + 10 * stats->lvl;
stats->life = stats->max_life;
}
if (stats->launch_lvlup == 110)
stats->launch_lvlup = 0;
if (stats->launch_lvlup != 0) {
animation(stats->lvl_up, 900, 5400, 100.0);
draw(win->window, stats->lvl_up->sprite);
stats->launch_lvlup++;
}
stats->max_life = 90 + 10 * stats->lvl;
draw_lifebarre(stats, win);
draw_xp(stats, win);
return stats;
}
|
a55245006cac0d6fa784ac4ed95ed543baab5abc
|
[
"C",
"Makefile"
] | 62
|
C
|
Artorius104/Tek1-myRPG
|
616433c7e06c334d0eee04b355f659e0b8369eab
|
865fd4c51843d5b933641f5e3ce070f8288490aa
|
refs/heads/master
|
<repo_name>davidvi11egas/burger<file_sep>/db/seeds.sql
INSERT INTO burgers (burger_name,devoured)
VALUES ('Cheeseburger','false'),
('Baconburger','false'),
('Veggieburger','false'),
('Doubleburger','true');
<file_sep>/config/connection.js
//BRINGING IN MYSQL ASSET
var mysql = require('mysql');
//DATABASE CRIDENTIALS
var mysql = require('mysql');
var connection;
if (process.env.JAWSDB_URL){
connection = mysql.createConnection(process.env.JAWSDB_URL);
}else {
connection = mysql.createConnection({
host: "localhost",
port: "8889",
user: "root",
password: "<PASSWORD>",
database: "burgers_db"
});
};
//CONNECT TO DATABASE + TEST
connection.connect(function (err) {
if (err) {
console.error("!ERROR!: " + err.stack);
return;
}
});
//EXPORT CONNECTION FOR ORM USAGE
module.exports = connection;
<file_sep>/README.md
# EAT-DA-BURGER!
# week 14 homework by <NAME>
# UCF Coding Boot Camp
## This app utilizes Node, Express, MySQL, and ORM.
## Once the server.js file is initiated... matrix dancers will provide you the link to the site.

## From there you will be taken to the main page, where you will see a list of burgers on the right that is pulled from the database.
## You have two options: 1. Eat a burger already on the list 2. Add your own burger to the list

## screen cap of the database:

|
2d8768c9b23834e1d18e09f18dcea5d336eedb44
|
[
"JavaScript",
"SQL",
"Markdown"
] | 3
|
SQL
|
davidvi11egas/burger
|
78e5c95fae5e01fb4d67fd659d848561d06c2026
|
00b7738a8dce055cb88fdc8b8ee5b29077930544
|
refs/heads/master
|
<file_sep>package com.example.recyclerview4orders;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class OrderListAdapter extends RecyclerView.Adapter<OrderListAdapter.ProductItemHolder> {
Context context;
ArrayList<OrderClass> order_list;
onItemClickListener mListener;
public interface onItemClickListener {
public void onItemClick(int position);
public void onPrintClick(int position);
}
public void setOnItemClickListener(OrderListAdapter.onItemClickListener listener) {
mListener = listener;
}
public OrderListAdapter(Context context, ArrayList<OrderClass> order_list) {
this.context = context;
this.order_list = order_list;
}
public class ProductItemHolder extends RecyclerView.ViewHolder {
TextView order_id,order_date,order_amount,order_payment_remaining,order_amount_paid;
TextView order_paid_display,order_pending_display;
TextView enter_pay,print_order;
LinearLayout linear_row;
ImageView go2details;
ImageView delete_icon;
public ProductItemHolder(View itemView, final onItemClickListener listener) {
super(itemView);
order_id = itemView.findViewById(R.id.row_order_id);
order_date = itemView.findViewById(R.id.row_order_date);
order_amount = itemView.findViewById(R.id.row_order_amount);
order_payment_remaining = itemView.findViewById(R.id.row_order_remaining);
order_amount_paid = itemView.findViewById(R.id.row_amount_paid);
order_paid_display = itemView.findViewById(R.id.order_status_paid);
order_pending_display = itemView.findViewById(R.id.order_status_pending);
enter_pay = itemView.findViewById(R.id.enter_pay1);
print_order = itemView.findViewById(R.id.print_order1);
enter_pay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
// go2details.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (listener != null) {
// int position = getAdapterPosition();
// if (position != RecyclerView.NO_POSITION) {
// listener.onItemClick(position);
// }
// }
// }
// });
// delete_icon.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if(listener != null){
// int position = getAdapterPosition();
// if(position != RecyclerView.NO_POSITION){
// listener.onPrintClick(position);
// }
// }
// }
// });
}
}
@NonNull
@Override
public ProductItemHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(context).inflate(R.layout.row_order_list, viewGroup, false);
ProductItemHolder pih = new ProductItemHolder(v, mListener);
return pih;
}
@Override
public void onBindViewHolder(@NonNull ProductItemHolder orderItemHolder, int i) {
OrderClass oc = order_list.get(i);
orderItemHolder.order_id.setText(oc.orderId);
orderItemHolder.order_date.setText(oc.date);
orderItemHolder.order_amount.setText(oc.orderCost);
orderItemHolder.order_payment_remaining.setText(oc.remaining);
orderItemHolder.order_amount_paid.setText(oc.paid);
orderItemHolder.enter_pay.setVisibility(View.VISIBLE);
orderItemHolder.print_order.setVisibility(View.VISIBLE);
if(oc.isPending){
orderItemHolder.order_pending_display.setVisibility(View.VISIBLE);
orderItemHolder.order_paid_display.setVisibility(View.GONE);
}
else{
orderItemHolder.order_paid_display.setVisibility(View.VISIBLE);
orderItemHolder.order_pending_display.setVisibility(View.GONE);
}
// productItemHolder.product_icon.setImageBitmap(product_list.get(i).product_image);
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
}
@Override
public int getItemCount() {
return order_list.size();
}
}
<file_sep>package com.example.recyclerview4orders;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.PersistableBundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.FormatFlagsConversionMismatchException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
ArrayList<OrderClass> list_order_details;
AlertDialog alertDialog;
TextView dialog_submit_button,dialog_full_payment;
EditText dialog_input_pay,dialog_input_total_pay;
RecyclerView rcv_orders;
int intTotalCost,intTotalRemaining,intTotalPaid;
LinearLayout add_order_button;
TextView TotalCost,TotalRemaining,TotalPaid,TotalPayButton,DialogSubmitPay,DialogTotalPay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TotalPayButton = findViewById(R.id.total_pay_button);
// TotalPayButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
// alertDialog = dialogBuilder.create();
// View dialog_view = getLayoutInflater().inflate(R.layout.dialog_layout_total_pay,null);
// alertDialog.setView(dialog_view);
// alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//
// DialogSubmitPay = dialog_view.findViewById(R.id.dialog_total_pay_submit);
// DialogTotalPay = dialog_view.findViewById(R.id.dialog_total_payment_text);
// dialog_input_total_pay = dialog_view.findViewById(R.id.dialog_edit_text_total_pay_input);
//
// DialogSubmitPay.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if(TextUtils.isEmpty(dialog_input_total_pay.getText().toString())){
// Toast.makeText(MainActivity.this, "Please enter amount to pay", Toast.LENGTH_SHORT).show();
// return;
// }
// }
// });
//
// }
// });
add_order_button = findViewById(R.id.add_order);
add_order_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Order added", Toast.LENGTH_SHORT).show();
}
});
TotalCost = findViewById(R.id.total_cost);
TotalRemaining = findViewById(R.id.remaining_balance);
TotalPaid = findViewById(R.id.total_paid);
intTotalCost = 0;
intTotalRemaining = 0;
intTotalPaid = 0;
rcv_orders = findViewById(R.id.recycler_order_list);
list_order_details = new ArrayList<>();
list_order_details.add(new OrderClass("01","A1306X","06 May 2019","8140","8140","0",true));
list_order_details.add(new OrderClass("02","A1305X","06 May 2019","11300","0","11300",false));
list_order_details.add(new OrderClass("03","A1304X","03 May 2019","5800","5800","0",true));
list_order_details.add(new OrderClass("04","A1303X","02 May 2019","2600","2600","0",true));
list_order_details.add(new OrderClass("05","A1302X","02 May 2019","4300","4300","0",true));
getTotalValues();
final OrderListAdapter adapter = new OrderListAdapter(getApplicationContext(),list_order_details);
adapter.setOnItemClickListener(new OrderListAdapter.onItemClickListener() {
@Override
public void onItemClick(final int position) {
// Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT).show();
if (list_order_details.get(position).isPending) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialog = dialogBuilder.create();
View dialog_view = getLayoutInflater().inflate(R.layout.dialog_layout,null);
alertDialog.setView(dialog_view);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog_submit_button = dialog_view.findViewById(R.id.dialog_submit);
dialog_full_payment = dialog_view.findViewById(R.id.dialog_full_payment_text);
dialog_input_pay = dialog_view.findViewById(R.id.dialog_edit_text_input1);
dialog_submit_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(TextUtils.isEmpty(dialog_input_pay.getText().toString())){
Toast.makeText(MainActivity.this, "Please enter amount to pay", Toast.LENGTH_SHORT).show();
return;
}
int pay_input = Integer.parseInt(dialog_input_pay.getText().toString());
int order_remaining = Integer.parseInt(list_order_details.get(position).remaining);
if(pay_input > order_remaining ){
Toast.makeText(MainActivity.this, "Payment higher than outstanding. Try Again", Toast.LENGTH_SHORT).show();
}
else{
// OrderClass oc = list_order_details.get(position);
int new_remaining = Integer.parseInt(list_order_details.get(position).getRemaining()) - pay_input;
int new_paid = Integer.parseInt(list_order_details.get(position).getPaid()) + pay_input;
list_order_details.get(position).setPaid(String.valueOf(new_paid));
list_order_details.get(position).setRemaining(String.valueOf(new_remaining));
if(new_remaining == 0){
// Toast.makeText(MainActivity.this, "yes", Toast.LENGTH_SHORT).show();
list_order_details.get(position).isPending = false;
}
alertDialog.dismiss();
adapter.notifyItemChanged(position);
getTotalValues();
// new Timer().schedule(new TimerTask() {
// @Override
// public void run() {
//
// }
// },1000);
}
}
});
dialog_full_payment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
list_order_details.get(position).setRemaining(String.valueOf(0));
list_order_details.get(position).setPaid(list_order_details.get(position).getOrderCost());
list_order_details.get(position).isPending = false;
alertDialog.dismiss();
adapter.notifyItemChanged(position);
getTotalValues();
}
});
// alertDialog.getWindow().getAttributes().windowAnimations = R.style.DialogTheme;
alertDialog.show();
}
else{
Toast.makeText(MainActivity.this, "Selected order already processed", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onPrintClick(int position) {
}
});
TotalPayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (list_order_details.get(list_order_details.size()-1).isPending) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialog = dialogBuilder.create();
View dialog_view = getLayoutInflater().inflate(R.layout.dialog_layout_total_pay,null);
alertDialog.setView(dialog_view);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
DialogSubmitPay = dialog_view.findViewById(R.id.dialog_total_pay_submit);
DialogTotalPay = dialog_view.findViewById(R.id.dialog_total_payment_text);
dialog_input_total_pay = dialog_view.findViewById(R.id.dialog_edit_text_total_pay_input);
DialogTotalPay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TotalPaid.setText(TotalCost.getText().toString());
TotalRemaining.setText("Rs 0" );
for(int i = 0;i < list_order_details.size();i++){
list_order_details.get(i).isPending = false;
list_order_details.get(i).remaining = "0";
list_order_details.get(i).paid = list_order_details.get(i).orderCost;
}
adapter.notifyDataSetChanged();
alertDialog.dismiss();
}
});
DialogSubmitPay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(TextUtils.isEmpty(dialog_input_total_pay.getText().toString())){
Toast.makeText(MainActivity.this, "Please enter amount to pay", Toast.LENGTH_SHORT).show();
return;
}
int pay_input1 = Integer.parseInt(dialog_input_total_pay.getText().toString());
int order_remaining1 = Integer.parseInt(TotalRemaining.getText().toString().substring(3));
if(pay_input1 > order_remaining1 ){
Toast.makeText(MainActivity.this, "Payment higher than outstanding. Try Again", Toast.LENGTH_SHORT).show();
}
else{
// order_remaining1 -= pay_input1;
// TotalRemaining.setText("Rs " + String.valueOf(order_remaining1));
// int total_paid = Integer.parseInt( TotalPaid.getText().toString().substring(3));
// total_paid += pay_input1;
// TotalPaid.setText(String.valueOf(total_paid));
for(int i =0;i < list_order_details.size();i++){
if(pay_input1 > 0) {
if (list_order_details.get(i).isPending) {
if (Integer.parseInt(list_order_details.get(i).remaining) < pay_input1) {
pay_input1 -= Integer.parseInt(list_order_details.get(i).remaining);
list_order_details.get(i).remaining = "0";
list_order_details.get(i).isPending = false;
list_order_details.get(i).setPaid(list_order_details.get(i).getOrderCost());
} else if ((Integer.parseInt(list_order_details.get(i).remaining) > pay_input1)&& (pay_input1 > 0)) {
int remaining = (Integer.parseInt(list_order_details.get(i).remaining)) - pay_input1;
list_order_details.get(i).remaining = String.valueOf(remaining);
int init_paid = Integer.parseInt(list_order_details.get(i).getPaid());
init_paid += pay_input1;
list_order_details.get(i).paid = String.valueOf(init_paid);
pay_input1 = 0;
break;
} else if(pay_input1 != 0){
list_order_details.get(i).remaining = "0";
list_order_details.get(i).isPending = false;
list_order_details.get(i).setPaid(list_order_details.get(i).getOrderCost());
pay_input1 = 0;
break;
}
}
}
}
alertDialog.dismiss();
adapter.notifyDataSetChanged();
}
getTotalValues();
}
});
alertDialog.show();
}
else{
Toast.makeText(MainActivity.this, "Payment for shop complete", Toast.LENGTH_SHORT).show();
}
}
});
LinearLayoutManager manager = new LinearLayoutManager(null);
rcv_orders.setLayoutManager(manager);
rcv_orders.setAdapter(adapter);
startIntroAnimation();
}
private void startIntroAnimation() {
rcv_orders.setTranslationX(rcv_orders.getWidth());
rcv_orders.setAlpha(0f);
rcv_orders.animate()
.translationX(0f)
.setDuration(1000)
.alpha(1f)
.setInterpolator(new AccelerateDecelerateInterpolator())
.start();
}
private void getTotalValues() {
intTotalCost = 0;
intTotalRemaining = 0;
intTotalPaid = 0;
for(OrderClass oc:list_order_details){
intTotalCost += Integer.parseInt(oc.getOrderCost());
intTotalRemaining += Integer.parseInt(oc.getRemaining());
intTotalPaid += Integer.parseInt(oc.getPaid());
}
TotalCost.setText("Rs " + String.valueOf(intTotalCost));
TotalRemaining.setText("Rs " + String.valueOf(intTotalRemaining));
TotalPaid.setText("Rs " + String.valueOf(intTotalPaid));
}
}
|
c32ce80caf5e0188b2eed777c9acb44ee046de77
|
[
"Java"
] | 2
|
Java
|
AmeerSaleem/RecyclerView4Orders
|
2d252e5da13a395fcd654ab13ee929c48a1f5786
|
c2b7d01cee5d1234b09d0b30382c4f4854bb489e
|
refs/heads/master
|
<file_sep>include $(THEOS)/makefiles/common.mk
SUBPROJECTS += libPImportWebServer
SUBPROJECTS += pimporthook
SUBPROJECTS += pimportsb
SUBPROJECTS += pimportsettings
include $(THEOS_MAKE_PATH)/aggregate.mk
<file_sep>include $(THEOS)/makefiles/common.mk
TWEAK_NAME = PImport
$(TWEAK_NAME)_FILES = /mnt/d/codes/PImport/pimporthook/PImport.xm
$(TWEAK_NAME)_FILES += /mnt/d/codes/PImport/pimporthook/SimpleExif/ExifContainer.m
$(TWEAK_NAME)_FRAMEWORKS = Foundation CydiaSubstrate UIKit CoreMedia CoreGraphics AVFoundation MobileCoreServices ImageIO QuartzCore CoreImage AssetsLibrary CoreLocation MapKit
$(TWEAK_NAME)_PRIVATE_FRAMEWORKS = StoreServices Preferences
$(TWEAK_NAME)_CFLAGS = -fobjc-arc
$(TWEAK_NAME)_LDFLAGS = -Wl,-segalign,4000
export ARCHS = armv7 armv7s arm64 arm64e
$(TWEAK_NAME)_ARCHS = armv7 armv7s arm64 arm64e
include $(THEOS_MAKE_PATH)/tweak.mk
<file_sep>include $(THEOS)/makefiles/common.mk
LIBRARY_NAME = libPImportWebServer
$(LIBRARY_NAME)_FILES = $(wildcard /mnt/d/codes/PImport/libPImportWebServer/*.m)
$(LIBRARY_NAME)_INSTALL_PATH = /usr/lib
$(LIBRARY_NAME)_FRAMEWORKS = UIKit Foundation CoreFoundation CFNetwork MobileCoreServices AssetsLibrary Photos
$(LIBRARY_NAME)_CFLAGS = -fobjc-arc -std=c++11
$(LIBRARY_NAME)_LDFLAGS = -lz -Wl,-segalign,4000
$(LIBRARY_NAME)_ARCHS = armv7 armv7s arm64 arm64e
export ARCHS = armv7 armv7s arm64 arm64e
include $(THEOS_MAKE_PATH)/library.mk
<file_sep>
#define PORT_SERVER 6729
#define PORT_SERVER_SHARE 60
#define kMaxIdleTimeSeconds 2
#define SERVER_TIMEOUT_SECONDS 3600
|
dc0823bb3cd7937cc8166bd44b49fb1e1bad0485
|
[
"C",
"Makefile"
] | 4
|
Makefile
|
julioverne/PImport
|
c2eb64822bed7e8fdadfef055f36b09120641c11
|
8828f4585dd89a85f4c61b58ea5da5526deb9bd7
|
refs/heads/master
|
<repo_name>cvan/sandbox-aframe<file_sep>/examples/monument/index.js
var AFRAME = window.AFRAME.aframeCore || window.AFRAME;
/* Components
——————————————————————————————————————————————*/
AFRAME.registerComponent('gamepad-controls', require('aframe-gamepad-controls'));
AFRAME.registerComponent('keyboard-controls', require('aframe-keyboard-controls'));
AFRAME.registerComponent('proxy-controls', require('aframe-proxy-controls'));
AFRAME.registerComponent('jump-ability', require('../../src/jump-ability'));
<file_sep>/README.md
# sandbox-aframe
<file_sep>/src/jump-ability.js
/**
* Adds jump ability on component.
*/
var ACCEL_G = -9.8, // m/s^2
EPS = 0.01;
module.exports = {
dependencies: ['position'],
/* Schema
——————————————————————————————————————————————*/
schema: {
on: { default: 'keydown:Space gamepadbuttondown:0' },
playerHeight: { default: 1.764 },
enableDoubleJump: { default: false },
distance: { default: 10 },
soundJump: { default: '' },
soundLand: { default: '' },
debug: { default: false }
},
/* Init / Deinit
——————————————————————————————————————————————*/
init: function () {
this.position = new THREE.Vector3();
this.raycaster = new THREE.Raycaster(
this.position.clone(), new THREE.Vector3(0, -1, 0), 0, this.data.playerHeight + EPS
);
this.isOnObject = true;
this.velocity = 0;
this.numJumps = 0;
var beginJump = this.beginJump.bind(this),
events = this.data.on.split(' ');
this.bindings = {};
for (var i = 0; i < events.length; i++) {
this.bindings[events[i]] = beginJump;
this.el.addEventListener(events[i], beginJump);
}
var scene = this.el.sceneEl;
if (scene.addBehavior) {
scene.addBehavior(this);
}
},
remove: function () {
for (var event in this.bindings) {
if (this.bindings.hasOwnProperty(event)) {
this.el.removeEventListener(event, this.bindings[event]);
delete this.bindings[event];
}
}
},
/* Render loop
——————————————————————————————————————————————*/
update: (function () {
var prevTime = NaN;
return function () {
var t = Date.now(),
tDelta = t - prevTime;
this.tick(t, tDelta);
prevTime = t;
};
}()),
tick: function (t, tDelta) {
var terrain = this.getTerrain();
if (Number.isNaN(tDelta)) return;
if (!terrain.length) {
if (this.data.debug) console.warn('[jump-ability] Cannot jump - no terrain found.');
return;
}
this.position.copy(this.el.getAttribute('position'));
this.raycaster.ray.origin.copy(this.position);
var intersections = this.raycaster.intersectObjects(terrain, true /* recursive */);
this.isOnObject = intersections.length > 0;
if (this.isOnObject && this.velocity < 0) {
this.velocity = 0;
this.numJumps = 0;
if (this.data.soundLand) {
this.el.querySelector(this.data.soundLand).emit('fire');
}
} else if (!this.isOnObject || this.velocity) {
this.position.y = Math.max(
this.position.y + this.velocity * tDelta / 300,
this.data.playerHeight
);
this.velocity += ACCEL_G * tDelta / 300;
}
this.el.setAttribute('position', this.position);
},
/* Jump
——————————————————————————————————————————————*/
beginJump: function () {
if (this.isOnObject || this.data.enableDoubleJump && this.numJumps === 1) {
this.velocity = 15;
this.numJumps++;
if (this.data.soundJump) {
this.el.querySelector(this.data.soundJump).emit('fire');
}
}
},
/* Terrain detection
——————————————————————————————————————————————*/
getTerrain: (function () {
var terrainObjects = [],
cached = false;
return function () {
// Cache terrain for performance.
if (cached) {
return terrainObjects;
}
if (this.data.debug) console.time('[jump-ability] getTerrain()');
var terrainSelector = this.el.sceneEl.getAttribute('terrain'),
terrainEls = this.el.sceneEl.querySelectorAll(terrainSelector),
pending = terrainSelector.split(',').length - terrainEls.length;
for (var i = 0, l = terrainEls.length; i < l; i++) {
if (terrainEls[i].object3D) {
terrainObjects.push(terrainEls[i].object3D);
} else {
pending++;
}
}
if (this.data.debug) {
console.timeEnd('[jump-ability] getTerrain()');
console.info('[jump-ability] %d terrain geometries found.', terrainObjects.length);
if (pending) {
console.info('[jump-ability] awaiting %d more terrain geometries', pending);
}
}
cached = !pending;
return terrainObjects;
};
}())
};
|
9613ced70cafbe2d36739455a4238580d980e509
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
cvan/sandbox-aframe
|
b4c1860db5ffefb342abfea674ca770a47ae6a86
|
e0acffb8b9bfd0771dd509ca6ead87fb49c45e10
|
refs/heads/master
|
<file_sep>package com.weiwei.security.dao;
import java.util.Optional;
import com.weiwei.security.vo.User;
public interface UserDao {
Optional<User> findByUsername(String username);
}
<file_sep>package com.weiwei.security.common;
public class Constants {
public static final String DBNAME_TRADE = "trade";
public static final String T_USER = "user";
}
<file_sep>package com.weiwei.security;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class AuthServerApplicationTests {
@LocalServerPort
private int port;
private TestRestTemplate template = new TestRestTemplate();
@Test
public void homePageProtected() {
ResponseEntity<String> response = template.getForEntity("http://localhost:" + port + "/uaa", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
String auth = response.getHeaders().getFirst("WWW-Authenticate");
assertFalse("Wrong header: " + auth, auth.startsWith("Bearer realm=\""));
}
@Test
public void loginSucceeds() {
ResponseEntity<String> response = template.getForEntity("http://localhost:" + port + "/uaa/login",
String.class);
String csrf = getCsrf(response.getBody());
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.set("username", "user");
form.set("password", "<PASSWORD>");
form.set("_csrf", csrf);
HttpHeaders headers = new HttpHeaders();
headers.put("COOKIE", response.getHeaders().get("Set-Cookie"));
RequestEntity<MultiValueMap<String, String>> request = new RequestEntity<MultiValueMap<String, String>>(form,
headers, HttpMethod.POST, URI.create("http://localhost:" + port + "/uaa/login"));
ResponseEntity<Void> location = template.exchange(request, Void.class);
assertEquals("http://localhost:" + port + "/uaa", location.getHeaders().getFirst("Location"));
}
private String getCsrf(String soup) {
Matcher matcher = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*").matcher(soup);
if (matcher.matches()) {
return matcher.group(1);
}
return null;
}
}
<file_sep>package com.weiwei.security.controller;
import java.security.Principal;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@RequestMapping("/user")
@ResponseBody
public Principal user(Principal user) {
return user;
}
}
|
564c38f2ba0d5d39e8c42c17a5c784dad87c0f98
|
[
"Java"
] | 4
|
Java
|
HZSF/AuthServer
|
9a276a79c3ad182423f2f542a3bb3d1837794cd8
|
254fea9ced07797c7dbe443528d5c0f9d3f58f6c
|
refs/heads/master
|
<file_sep>//função para a validação do formulário
function validaform(frm)
{
//valida nome
if (frm.tf_nome.value == "")
{
alert("Informe o Nome!");
frm.tf_nome.focus();
return false;
}
//valida email
if (frm.CLI_EMAIL.value == "")
{
alert("Informe o e-mail!");
frm.CLI_EMAIL.focus();
return false;
}
//valida cpf
if (frm.CLI_CPF.value == "")
{
alert("Informe o CPF!");
frm.CLI_CPF.focus();
return false;
}
//valida data nascimento
if (frm.CLI_DATANASC.value == "")
{
alert("Informe o Data Nascimento!");
frm.CLI_DATANASC.focus();
return false;
}
//valida endereco
if (frm.CLI_ENDERECO.value == "")
{
alert("Informe o Endereço!");
frm.CLI_ENDERECO.focus();
return false;
}
//valida cep
if (frm.CLI_CEP.value == "")
{
alert("Informe o CEP!");
frm.CLI_CEP.focus();
return false;
}
//valida cidade
if (frm.CLI_CIDADE.value == "")
{
alert("Informe o Cidade!");
frm.CLI_CIDADE.focus();
return false;
}
//valida estado
if (frm.textfield.value == "")
{
alert("Informe o Estado");
frm.textfield.focus();
return false;
}
//valida telefone
if (frm.CLI_FONE.value == "")
{
alert("Informe o Telefone!");
frm.CLI_FONE.focus();
return false;
}
}
//função que cria as mascaras
function formatar_mascara(src, mascara) {
var campo = src.value.length;
var saida = mascara.substring(0,1);
var texto = mascara.substring(campo);
if(texto.substring(0,1) != saida) {
src.value += texto.substring(0,1);
}
}
function Numero(e)
{
navegador = /msie/i.test(navigator.userAgent);
if (navegador)
var tecla = event.keyCode;
else
var tecla = e.which;
if(tecla > 47 && tecla < 58) // numeros de 0 a 9
return true;
else
{
if (tecla != 8) // backspace
return false;
else
return true;
}
}
/*funcao que carrega o combo box com o que for digitado no textfiel e vice versa.
obs.: a funcao toUpperCase server para colocar tudo em maiuscula tanto o que esta
sendo digitado quanto o que esta sendo pesquisado mas tudo isso via codigo para o
usuario nao se preocupar com o case sensitive*/
var i = 0;
var aux = '';
function buscar(valor) {
for (i = 0; i < document.getElementById('EST_CODIGO').length;i=i+1) {
if (document.getElementById('EST_CODIGO').options[i].value.toUpperCase() == valor.toUpperCase() ) {
document.getElementById('EST_CODIGO').options[i].selected = true;
}
}
}<file_sep># store_automacao
Projeto de Avaliação Java EE
|
8e453188aa58c6bd1850a98b5547e1738f6dd35a
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
antunesdevweb/store_automacao
|
a419546531e734fe02bb5dd9cb7c403a018e5854
|
f388ed55926c517e8a3480325a3996ed0797de23
|
refs/heads/main
|
<repo_name>kalleniang/Demo<file_sep>/dist/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PortFolio</title>
<link rel="shortcut icon" href="favicon/favicon.ico">
<link rel="stylesheet" href="fontawesome-free-5.15.1-web/css/all.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<nav class="main-nav">
<div class="nav-menu">
<div class="logo">
<img src="images/logo.png" alt="logo">
</div>
<div class="toggle-collapse">
<div class="toggle-icon">
<i class="fas fa-bars"></i>
</div>
</div>
<ul class="nav-items">
<li class="home"><a href="index.html">Home</a></li>
<li class="about"><a href="#about">About</a></li>
<li class="contact"><a href="#contact">Contact</a></li>
<li class="project"><a href="#projects">Projects</a></li>
</ul>
</div>
</nav>
</header>
<div class="container">
<div>
<h1>This is one of those things</h1>
</div>
<section id="section1">
<div>
<h2>Welcome!</h2>
<p>Yeah, I have no idea what I'm doing</p>
<p>Just keep on reading, maybe you'll find something interesting.</p>
</div>
</section><!-- /section 1 -->
<section id="about">
<div>
<h2>About Me</h2>
<span class="avatar">
<img src="images/kallzo.jpg" alt="kallzo">
</span>
<p>My name is <strong><NAME></strong>, I like fried chicken, <em>but who doesn't</em>...
</p>
<p>The year was 1992,... Nevermind.</p>
<p>I'm Kalle, and I'm a self-taught programmer. Because, why not. I love programming, and computers, and
anything related to
tech...</p>
<p>I just turned <del>27</del>, (actually that was last year, now I'm 28) and I remembered that when I was a
kid, probably around 2, I said to myself
"I'm
gonna make a really ugly website when I turn 27".</p>
<p>That's not actually true, I don't even remember where I was, or what I was doing when I was 2.</p>
<p>So, if you remember something about yourself when you were 2, feel free to tell me. Unless you're actually a
2 year old, then you might wanna tell me how is it that you can use the internet and type things.</p>
<p>"Who am I?" Well, if you're a linux user, you should open up the terminal and type
<code>whoami</code> and you'll find out.</p>
</div>
<div>
<p>You might be wondering "<em>What the heck is this?</em>" Well, I've been wondering the same
thing...
</p>
<p>So, this is just a simple project, I think it's supposed to be about me, but even I don't know what I'm
about...</p>
<p>Does it look ugly? Yes, but I'm also ugly, so it makes sense.</p>
<p>It didn't take me long to make this at all, and there are no frameworks involved...</p>
<p>Just pure HTML, CSS, and JavaScript.</p>
<p>Who knows, maybe I'll work on it and make it look prettier... I doubt that'll happen though.</p>
<p>What else,... I like to mess around with other programming languages like Python, and Java.</p>
<p>I'm a web developer though, but I'm just curious. Every now and then I feel like coding in a different
language, and Python and Java are my two favorites, so they're my go to.</p>
<p>When it comes to web, I like using JavaScript, but I'm not much of node guy, so I like to use PHP on the
backend. Maybe some day I'll get to a point where I have to use nodejs and I'll get into it, but for now it's
PHP and MYSQL. Because I'm a simple guy, and all those stacks out there, like the <mark>MERN stack</mark>, and
the <mark>MEAN stack</mark> are just not on my radar yet.</p>
</div>
</section><!-- /section 2 -->
<section id="contact">
<div>
<h2>Contact Info</h2>
<p>You wanna know where I live, don't you?</p>
<p>It's fine I'm gonna tell you...</p>
<p>E-mail: <EMAIL></p>
<p>Phone: (+33) 758 08 96 58</p>
<p>You can also find me on Twitter (actually I just remembered that I quit Twitter), so I guess it's Instagram
(until I quit), but don't don't worry, I'm not quitting github, I'll always be there for you.</p>
<p>Sorry Facebook, You didn't make the cut... But now that I think about it, you kinda did, since you own
Instagram... Oh well.</p>
<p>Feel free to contact me...</p>
</div>
<div>
<p>Well, this looks terrible... Any ideas?</p>
<p>You know, Maybe I need a little bit of inspiration.</p>
<p>But before inspiration comes, let's just try and focus on the bright side of things, like how beautiful this
page looks. I mean, have you ever seen anything like it? This is a masterpiece design.</p>
<p>So if you need someone to fix you up something like this, just hit me up, I'll be glad to cover your entire
life with some style.</p>
<p>Did I tell you where I live? No I didn't... Peace</p>
</div>
</section><!-- /section 3 -->
<section id="projects">
<h2>Coming Soon!</h2>
</section><!-- /section 4 -->
</div><!-- /container -->
<footer>
<div class="main-footer">
<div class="info">
<h3>Info</h3>
<p><NAME></p>
<p>Copyright © Kalle 2020 All Rights Reserved</p>
</div><!-- /div1 -->
<div class="social">
<h3>Social</h3>
<p>Find me on Social Media</p>
<!-- <span>
<a href="https://twitter.com/Kallzo0" target="_blank"><i class="fab fa-twitter"></i> Twitter</a> |
</span> -->
<span>
<a href="https://www.instagram.com/kallzo/" target="_blank"><i class="fab fa-instagram"></i> Instagram</a> |
</span>
<span>
<a href="https://github.com/kallzo" target="_blank"><i class="fab fa-github"></i> Github</a> |
</span>
</div><!-- /div2 -->
<div class="contact">
<h3>Contact</h3>
<p>E-mail: <EMAIL></p>
<p>Phone: (+33) 758 08 96 58</p>
</div>
</div>
</footer>
<script src="js/script.js"></script>
</body>
</html><file_sep>/dist/README.md
#My Project
I think it's portfolio, but I'm not sure.
I was going for a portfolio, but ended up with... I don't know
<file_sep>/dist/js/script.js
let home = document.querySelector("#section1");
let about = document.querySelector("#about");
let contact = document.querySelector("#contact");
let project = document.querySelector("#projects");
let homeBtn = document.querySelector(".home");
let aboutBtn = document.querySelector(".about");
let contactBtn = document.querySelector(".contact");
let projectBtn = document.querySelector(".project");
let container = document.querySelector(".container");
projectBtn.addEventListener("click", function (e) {
e.preventDefault();
container.childNodes[1].style.display = "none";
home.style.display = "none";
about.style.display = "none";
contact.style.display = "none";
project.style.display = "initial";
container.style.background = "white";
container.style.borderRadius = "10px";
aboutBtn.style.display = "none";
contactBtn.style.display = "none";
});
let newH3 = document.createElement("h3");
let el = project.appendChild(newH3);
el.appendChild(document.createTextNode("Now go home, You're drunk!"));
let show = false;
let nav = document.querySelector(".main-nav");
let toggle = document.querySelector(".toggle-collapse");
let navItems = document.querySelector(".nav-items");
toggle.addEventListener("click", function (e) {
e.preventDefault();
if (show == false) {
// nav.style.height = "13rem";
nav.style.overflow = "initial";
nav.style.transition = "ease-in-out 2s";
navItems.style.display = "flex";
// navItems.style.flexDirection = "column";
show = true;
} else if (show == true) {
// nav.style.height = "0";
nav.style.overflow = "hidden";
navItems.style.display = "none";
show = false;
}
});
|
e8466d7a9b32a41fbcd50f8825aaf5e96f0b855c
|
[
"Markdown",
"JavaScript",
"HTML"
] | 3
|
HTML
|
kalleniang/Demo
|
c4382c0e3f99a9ef126da17dc776c0abe8143e96
|
dec0680c54adb15a70f62baaef1b6966e57d0e9e
|
refs/heads/master
|
<file_sep> // for (std::list<int>::iterator it=triv_list.begin(); it != upto; ++it){
// Do nothing here as we do not need to grab the data, but currently, the element is stored
// through the iterator - *it.
//} // Tranverse top k elements from list and record time.
// Set up iterator for list so it will only read up to k elements.
//std::list<triv>::iterator upto = triv_list.begin();
// Increment the iterator to stop at the k+1 element;
//for (int p = 0; p < k; p++ ){
// upto = ++upto;
// }<file_sep>// testlist.cpp
// Used to test list transversal with iterator.
// <NAME>
// April 6, 2014
#include <iostream>
#include <list>
int main ()
{
int myints [] = {75,23,65,42,13};
std :: list <int> mylist(myints, myints+5);
std::cout << "mylist contains:";
std::list<int>::iterator derp = mylist.begin();
for (int p = 0; p<5; p++)
derp = ++derp;
for (std::list<int>::iterator it=mylist.begin(); it != derp; ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}<file_sep>// benchmarks.cpp
// Used to benchmark specific data structures. Currently benches lists, stack, and queue.
// <NAME>
// March 30, 2014
#include "benchmarks.hpp"
int main(){
// Tests # of n data from the interval of 100000 to 1000000
for (int n = 100000; n <= 1000000; n=n+100000){
benching_structures(n);
}
return 0;
}<file_sep>// <NAME>
// helloworld.cpp
// April 5, 2014
// Used to retest my c++ abilities
#include <iostream>
#include <string>
using namespace std;
//Chrono typedefs
typedef std::chrono::microseconds microseconds;
int main(){
auto start = std::chrono::system_clock::now();
cout << "Hello World" << endl;
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
cout << elapsed.count() << " microseconds" <<'\n';
return 0;
}<file_sep>// benchmarks.hpp
// Definitions and Functions assisting in benchmarking of data strcutures
// <NAME>
// March 30, 2014
#include <chrono>
#include <stack>
#include <deque>
#include <list>
#include <iostream>
#include <random>
// Chrono typedefs
typedef std::chrono::microseconds microseconds;
// Number of repetions in each test
static const std::size_t REP = 10;
/************************ Struct Defintiion ******************************/
struct triv {
std::size_t x;
bool operator<(const triv &other) const { return x < other.x; }
};
/************************************************************************/
/************************ Function Declarations **************************/
// Main benching function for inserting
void benching_insert(int numberOfInput);
// Benching for insert from top.
microseconds insert_deque(int numberOfInput);
microseconds insert_list(int numberOfInput);
microseconds insert_stack(int numberOfInput);
// Benching for sort.
microseconds sort_deque(int numberOfInput);
microseconds sort_list(int numberOfInput);
// Benching for destruction.
microseconds destruction_deque(int numberOfInput);
microseconds destruction_list(int numberOfInput);
microseconds destruction_stack(int numberOfInput);
// Benching for getting top elements and deletion.
microseconds top_deque(int numberOfInput, int k);
microseconds top_list(int numberOfInput, int k);
microseconds top_stack(int numberOfInput, int k);
/************************************************************************/
/************************* Main Functions ******************************/
// benching_insert
// int numberOfInput - The number of data that will be inserted into the data structures.
// Instantiates tests for inserts of the data strucutres.
// List will have data pushed from the back.
// Stack will have data inserted by push from the back.
// Deque will have data be inserted by pushing from the back.
void benching_structures(int numberOfInput){
// Output the number N to the console.
std::cout << "The number of inputs, n, for this benchmark is " << numberOfInput << std::endl;
// Initialize the variables to hold the total time of inserts for data structures.
microseconds results_insert_deque (0);
microseconds results_insert_list (0);
microseconds results_insert_stack (0);
microseconds results_sort_deque (0);
microseconds results_sort_list (0);
microseconds results_distruct_deque (0);
microseconds results_distruct_list (0);
microseconds results_distruct_stack (0);
microseconds results_top_deque (0);
microseconds results_top_list (0);
microseconds results_top_stack (0);
// Iterate through the number of repetitions and call the insert functions at each.
for (std::size_t i = 0; i < REP; i++){
// Calculate the time it takes for each data structure inserts.
// Add up time for each data strucutre specifically.
// Deque inserts.
results_insert_deque += insert_deque(numberOfInput);
// List inserts.
results_insert_list += insert_list(numberOfInput);
// Stack inserts.
results_insert_stack += insert_stack(numberOfInput);
// Deque sort.
results_sort_deque += sort_deque(numberOfInput);
// List sort.
results_sort_list += sort_list(numberOfInput);
// Deque destruct.
results_distruct_deque += destruction_deque(numberOfInput);
// List destruct.
results_distruct_list += destruction_list(numberOfInput);
// Stack destruct.
results_distruct_stack += destruction_stack(numberOfInput);
// Deque top k elements.
results_top_deque += top_deque(numberOfInput, numberOfInput/2);
// List top k elements.
results_top_list += top_list(numberOfInput, numberOfInput/2);
// Stack top k elements.
results_top_stack += top_stack(numberOfInput, numberOfInput/2);
}
// Output the average of the inserts depending on the number of repetitions set.
std::cout << "Deque insert from back: " << results_insert_deque.count()/REP << std::endl;
std::cout << "List insert from back: " << results_insert_list.count()/REP << std::endl;
std::cout << "Stack inserts from back: " << results_insert_stack.count()/REP << std::endl;
std::cout << "Deque sort: " << results_sort_deque.count()/REP << std::endl;
std::cout << "List sort: " << results_sort_list.count()/REP << std::endl;
std::cout << "Deque destruction: " << results_distruct_deque.count()/REP << std::endl;
std::cout << "List destruction: " << results_distruct_list.count() /REP << std::endl;
std::cout << "Stack destruction: " << results_distruct_stack.count()/REP << std::endl;
std::cout << "Deque top k (#ofelements/2=" << numberOfInput/2 <<") elements: " << results_top_deque.count()/REP << std::endl;
std::cout << "List top k (#ofelements/2=" << numberOfInput/2 <<") elements: " << results_top_list.count()/REP << std::endl;
std::cout << "Stack top k (#ofelements/2=" << numberOfInput/2 <<") elements: " << results_top_stack .count()/REP << std::endl;
}
/************************************************************************/
/****************************** Insert ********************************/
// insert_deque
// int numberOfInput - The number of data that will be inserted into the deque.
// Insert function for deque. Data will be inserted via push to the back.
// Returns the time elapsed in microseconds
microseconds insert_deque(int numberOfInput){
// Initialize the deque.
std::deque<triv> trivial_deque;
// Push j into back of deque up to the given number of input and time it.
// Data being pushed will be of the strucutre triv with size_t as an attribute..
auto start = std::chrono::system_clock::now();
for (std::size_t j = 0; j < numberOfInput; j++){
triv triv_data;
triv_data.x = j;
trivial_deque.push_back(triv_data);
}
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<microseconds>(end - start);
return elapsed;
}
// insert_list
// int numberOfInput - The number of data that will be inserted into the list.
// Insert function for list. Data will be pushed at the back of the list.
// Returns the time elapsed in microseconds.
microseconds insert_list(int numberOfInput){
// Initialize the list
std::list<triv> trivial_list;
// Push j into back of list up to the given number of input and time it.
// Data being pushed to the front of the list will be of triv with size_t as an attribute.
auto start = std::chrono::system_clock::now();
for (std::size_t j = 0; j < numberOfInput; j++){
triv triv_data;
triv_data.x = j;
trivial_list.push_back(triv_data);
}
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<microseconds>(end - start);
return elapsed;
}
// insert_stack
// int numberOfInput - The number of data that will be inserted into the list.
// Insert function for stack. Data will be pushed onto it.
// Returns the time elapsed in microseconds.
microseconds insert_stack(int numberOfInput){
// Initialize the stack.
std::stack<triv> trivial_stack;
// Push j onto stack to the given number of input and time it.
// Data being pushed onto stack will be of triv with size_t as an attribute.
auto start = std::chrono::system_clock::now();
for (std::size_t j = 0; j < numberOfInput; j++){
triv triv_data;
triv_data.x = j;
trivial_stack.push(triv_data);
}
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<microseconds>(end - start);
return elapsed;
}
/************************************************************************/
/****************************** Sort **********************************/
// sort_deque
// int numberOfInput - Number of data in the deque.
// Sorts the given data in the deque and return time elapsed in microseconds.
// Fake random data will be pushed from the back.
microseconds sort_deque(int numberOfInput){
//Instatiate trivial deque with random data.
std::deque<triv> triv_deque;
for (std::size_t j = 0; j < numberOfInput; j++){
triv triv_data;
triv_data.x = rand()%numberOfInput;
triv_deque.push_back(triv_data);
}
// Sort the data using std::sort and time it
auto start = std::chrono::system_clock::now();
std::sort(std::begin(triv_deque), std::end(triv_deque));
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<microseconds>(end - start);
return elapsed;
}
// sort_list
// int numberOfInput - Number of data in the list.
// Sorts the given data in the list and returns time in microseconds.
// Fake random data will be pushed from the back of the list.
microseconds sort_list(int numberOfInput){
//Instantiate trivial list with random data.
std::list<triv> triv_list;
for(std::size_t j =0; j < numberOfInput; j++){
triv triv_data;
triv_data.x = rand()%numberOfInput;
triv_list.push_back(triv_data);
}
// Sort using the given containers sort function and time it.
auto start = std::chrono::system_clock::now();
triv_list.sort();
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<microseconds>(end - start);
return elapsed;
}
/************************************************************************/
/******************************** Destruction ********************************/
// destruction_deque
// int numberOfInput - number of data that needs to be deleted
// Calculates time it takes to fully delete the deque given the number of input.
// Returns the time in microseconds.
microseconds destruction_deque(int numberOfInput){
// Instantiate deque with random data.
std::deque<triv> triv_deque;
for (std::size_t j = 0; j < numberOfInput; j++){
triv triv_data;
triv_data.x = rand()%numberOfInput;
triv_deque.push_back(triv_data);
}
//Record time of clearing the deque using the given container function.
auto start = std::chrono::system_clock::now();
triv_deque.clear();
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<microseconds>(end - start);
return elapsed;
}
// destruction_list
// int numberOfInput - number of data that needs to be deleted
// Calculates time it takes to fully delete the list given the number of input.
// Returns the time in microseconds.
microseconds destruction_list(int numberOfInput){
//Instantiate trivial list with random data.
std::list<triv> triv_list;
for(std::size_t j =0; j < numberOfInput; j++){
triv triv_data;
triv_data.x = rand()%numberOfInput;
triv_list.push_back(triv_data);
}
// Delete using the given containers sort function and time it.
auto start = std::chrono::system_clock::now();
triv_list.clear();
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<microseconds>(end - start);
return elapsed;
}
// destruction_stack
// int numberOfInput - number of data that needs to be deleted
// Calculates time it takes to fully delete the stack given the number of input.
// Returns the time in microseconds.
microseconds destruction_stack(int numberOfInput){
// Instantiate stack with random data.
std::stack<triv> triv_stack;
for (std::size_t j = 0; j < numberOfInput; j++){
triv triv_data;
triv_data.x = rand()%numberOfInput;
triv_stack.push(triv_data);
}
// Pop till empty and time it.
auto start = std::chrono::system_clock::now();
while ( ! triv_stack.empty() ){
triv_stack.pop();
}
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<microseconds>(end - start);
return elapsed;
}
/************************************************************************/
/******************************** Top k elements********************************/
// top_deque
// int numberOfInput - number of inputed elements
// int k - number of elements being pulled from the top.
// Pulls out the top k elements in the deque and deletes them.
// Returns time it takes in microseconds.
microseconds top_deque(int numberOfInput, int k){
// Instantiate deque with random data.
std::deque<triv> triv_deque;
for (std::size_t j = 0; j < numberOfInput; j++){
triv triv_data;
triv_data.x = rand()%numberOfInput;
triv_deque.push_back(triv_data);
}
// Pop top k elements and record it.
auto start = std::chrono::system_clock::now();
for(int z = 0; z < k; z++){
triv_deque.pop_front();
}
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<microseconds>(end - start);
return elapsed;
}
// top_list
// int numberOfInput - number of inputed elements
// int k - number of elements being pulled from the top.
// Pulls out the top k elements in the list and deletes.
// Returns time it takes in microseconds.
microseconds top_list(int numberOfInput, int k){
//Instantiate trivial list with random data.
std::list<triv> triv_list;
for(std::size_t j =0; j < numberOfInput; j++){
triv triv_data;
triv_data.x = rand()%numberOfInput;
triv_list.push_back(triv_data);
}
// Traverse and pop!
auto start = std::chrono::system_clock::now();
for (int z = 0; z < k; z++){
triv_list.pop_front();
}
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<microseconds>(end - start);
return elapsed;
}
// top_stack
// int numberOfInput - number of inputed elements
// int k - number of elements being pulled from the top.
// Pulls out the top k elements in the stack.
// Returns time it takes in microseconds.
microseconds top_stack(int numberOfInput, int k){
// Instantiate stack with random data.
std::stack<triv> triv_stack;
for (std::size_t j = 0; j < numberOfInput; j++){
triv triv_data;
triv_data.x = rand()%numberOfInput;
triv_stack.push(triv_data);
}
// Pop top k elements from stack and record time.
auto start = std::chrono::system_clock::now();
for(int z = 0; z < k; z++){
triv_stack.pop();
}
auto end = std::chrono::system_clock::now();
microseconds elapsed = std::chrono::duration_cast<microseconds>(end - start);
return elapsed;
}
/************************************************************************/
|
207a050702a1a4055c9dd4430703ffba49acdab4
|
[
"C++"
] | 5
|
C++
|
gching/DataStructureForTesting
|
0609a514461e5b646088cbfc8eed04515901459b
|
5e9924883911ff9dc1777f066082fc01926d4473
|
refs/heads/master
|
<repo_name>marangiop/kmer_identifier<file_sep>/README.md
# kmer_identifier
This is the repository for the Bioinformatics Programming and System Management coursework as part of the MSc in Synthetic Biology and Biotechnology.
Kmer_Identifier is a Python-based programme facilitates the identification of short nucleotide subsequences (i.e. kmers) with unexpected distributions in biological data generated from Next generation sequencing platforms. It is specifically designed for analysing FASTQ-formatted files, one of the most common and most accepted file format for storing the output of high-throughput next generation sequencing platforms.
Inputs
Kmer length = integer that specifies the length of the subsequence in number of nucleotide bases that is used to check the sequencing data against (i.e. kmer length of 2 = 2 bases long kmers ; 5 = 5 bases long kmers).
Reporting threshold = integer that allows to specify how many times does an observed count for a given kmer have to be greater than the expected count for that kmer such that the kmer is reported in a given run of Kmer_Identifier. For example, a reporting threshold of 2 means that Kmer_Identifier will only report kmer sequences that have an observed count at least 2 times greater than it would be expected if that kmer was at that position just by chance.
<file_sep>/submission_code.py
# -*- coding: utf-8 -*-
"""
Created on Sun May 6 23:24:28 2018
@author: maran
"""
from __future__ import division
#STEP 1: Extraction of DNA sequences from the input file
while True: #This while loop will continute infinetely unless stopped when a condition is met
Actual_file_name = input("Enter file name including .fastq extension : \n ") #Allows user to enter the name of the file
if Actual_file_name.endswith('.fastq'): # Checks whether the file name entered by the user contains the string 'fastq' at the end
break #If the above condition is fulfilled, the while loop will be exited
else:
print("Error! Please enter an input file in .fastq format!") #Prints this error statement and re-starts the loop.
def DNA_sequences_extractor(file_name):
my_file = open(file_name)
extracted = []
for line in my_file: #This for loop treats the file as a list of lines and interates over each line
extracted.append(line.rstrip("\n"))
return extracted[1::4] #This function returns every 4th line starting from element with index 1 from the list 'extracted'
extracted_DNA_sequences=DNA_sequences_extractor(file_name=Actual_file_name)
#_____________________________________________________________________________________________________________________________
#STEP 2: Generation of a list of kmers for each sequence
while True: #This while loop will continute infinetely unless stopped when a condition is met
try:
k_value = int(input("Enter value of kmer length: \n ")) #Allows user to enter the kmer length and checks whether it is an integer
break #If the above condition is fulfilled, the while loop will be exited
except: #If there is an exception
print("That is not a valid number. Please insert an integer") #Prints this error statement and re-starts the loop.
def kmers_generator(dna_sequence_list, kmer_length):
kmers = []
for dna_sequence in dna_sequence_list:#This for loop iterates over a list of DNA sequences provided
for start in range(len(dna_sequence) - kmer_length + 1): #Thi for loop iterates over every starting position in the DNA sequence. Subtracting k and adding 1 allows to stop the range() so that incomplete kmers at the end of the sequence are not generated.
stop = start + kmer_length #This calculates the upper limit of the slice taken from the DNA sequence to generate the kmers.
kmer = dna_sequence[start:stop] #This generates a kmer of desired kmer length at that position in the DNA sequence
if kmer not in kmers: #This allows to append the kmers that are not already present in the list kmers.
kmers.append(kmer)
return kmers #This will generate a list of non-redundant kmers for a given list of sequences
all_kmers= kmers_generator(dna_sequence_list=extracted_DNA_sequences, kmer_length=k_value)
#_____________________________________________________________________________________________________________________________
#STEP 3:Generation of a collection of counts at each position across all the sequences for each kmer
def count_kmer_at_positions_across_sequences(dna_list, kmer_length, kmer_1):
kmers= {}
for dna_sequence in dna_list:
for position in range(len(dna_sequence)-kmer_length+1):
kmer= dna_sequence[position:position+kmer_length]
if kmer == kmer_1: #This checks whether the kmer being generated at that position (kmer) is equal to any kmer that is fed into the function (kmer_1)
kmers[position]= kmers.get(position, 0) +1 #This looks up the current count for that position and adds 1. The position acts as a key in the dict and the count is a stored as an integer value assigned to each position
for position in range(len(dna_sequence) - kmer_length + 1):
if position not in kmers: #If a position has not been assigned any count and is therefore not present in the dict kmers, which holds the count at each position
kmers[position] = 0 #The default value of such entry is set to 0
return kmers #This returns a dict holding the count of a given kmer at all positions across a list of DNA sequences.
dict_of_dicts_counts_kmers={}
for kmer in all_kmers:
dict_of_dicts_counts_kmers[kmer]= count_kmer_at_positions_across_sequences(dna_list=extracted_DNA_sequences, kmer_length=k_value, kmer_1= kmer) #Each dict produced from feeding into the function each given kmer from the list of non-redundant kmers "all_kmers" is assigned to a new key, which corresponds to each given kmer. In this way a dict of dicts is generated.
#_____________________________________________________________________________________________________________________________
#STEP 4:Calculation of the expected count for each kmer
def kmer_expected_counts(dna_list, kmer_length):
sequence_length_minus_kmer_length= len(dna_list[0])-kmer_length + 1 #This corresponds to the number of possible starting positions in a given sequence. In this case it is calculated based on the first sequence of the list of extracted sequence, but any other sequence could be used as it is assumed that all sequences have the same length
f = {}
for dna_sequence in dna_list:
for position in range(len(dna_sequence)-kmer_length + 1):
kmer = dna_sequence[position:position+kmer_length]
f[kmer] = f.get(kmer, 0) + 1 #This looks up the current count for that kmer and adds 1.
for kmer, count in f.items(): #This for loop iterates over every kmer and count in the dict f
f[kmer]= count/sequence_length_minus_kmer_length # Each kmer is now assigned to the total count of that kmer devided by sequence_length_minus_kmer_length
return f #This returns a dict that holds the expected count for each kmer across all the sequences
dict_expected_counts = kmer_expected_counts(dna_list = extracted_DNA_sequences, kmer_length= k_value)
#_____________________________________________________________________________________________________________________________
#STEP 5: Comparing the expected count and the observed count for each kmer at each position
while True: #This while loop will continute infinetely unless stopped when a condition is met
try:
threshold_value= int(input("Enter value of reporting threshold: \n ")) #Allows user to enter the threshold value
break #If the above condition is fulfilled, the while loop will be exited
except: #If there is an exception
print ("That is not a valid number. Please insert an integer") #Prints this error statement and re-starts the loop.
def kmer_flagging(kmer, threshold, expected):
for kmer1, dictionary in dict_of_dicts_counts_kmers.items():
if kmer1 == kmer: #This checks whether the kmer found in the list of observed counts (kmer) is equal to any kmer that is fed into the function (kmer_1)
for position, observed_count in dictionary.items(): #This for loop iterates over every position and observed count in each dictionary
if (observed_count/expected) > threshold: #The following command is performed only for those kmers whose observed count devided by its respective expected count is greater than a value that is assigned by the user to the variable 'threshold' through raw_input function
return kmer, int(expected), dictionary.values() #The function returns the kmer sequence, the expected count value rounded up to a whole number and the counts for that kmer at each position
#_____________________________________________________________________________________________________________________________
#STEP 6: Generation of an output file that stores information about ‘suspicious’ kmers
my_file = open(Actual_file_name.rstrip('.fastq') + "_" + "kmer_length" + "_" + str(k_value) + "_" + "reporting_threshold" + "_" + str(threshold_value) + '.txt', "w") # Automatically defines a file name that includes the input file name stripped of the .fastq extension and the kmer legnth and reporting threshold values. The '.txt' string is automatically added at the end of each output file name. This enables it to be opened with a word processor like Notepad or Microsoft Word
for kmer0, expected_count in dict_expected_counts.items(): #This for loop iterates over every kmer and expected count in the dict holding the expected counts
if kmer_flagging(kmer=kmer0,threshold=threshold_value, expected=expected_count) != None: #This checks whether a given kmer does not return None after it has been fed into the kmer_flagging() function.
output = str(kmer_flagging(kmer=kmer0,threshold=threshold_value, expected=expected_count)) #Every kmer is fed into function kmer_flagging and the returned information is stored as a string in the variable output
my_file.write('%s \n' %output) #Writes the information stored in variable output to the output file and adds a new line in the file
my_file.close()
|
4c0322ef9a7600350254da42696080364a64432b
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
marangiop/kmer_identifier
|
e0c57261c56bc43f5703f81dfacc91da5c5d86c1
|
b596444d38099bfc199ec56c739284aa81adffb0
|
refs/heads/master
|
<file_sep>package mx.com.AleDominguez.HolaSpring;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller //controlador tipo spring MVC
@Slf4j
public class ControladorInicio {
@GetMapping("/")
public String inicio() {
log.info("Ejecutando el controlador de tipo Spring MVC");
return "index";
}
}
|
bf0e761428a7042f95d34d19a620525456f12cfe
|
[
"Java"
] | 1
|
Java
|
AleDgz/HelloWorldSpring02
|
aebda3e0a9818dd3eb8b4595972ec13bbd0a59ef
|
e3e55973ea39b7d73666908cfdddeb689844ae5f
|
refs/heads/main
|
<repo_name>SheferSA/space-web<file_sep>/forms1.py
from flask_wtf import FlaskForm
from wtforms import SubmitField, StringField, RadioField, SelectField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired
class AddFriendsForm(FlaskForm):
request_id = StringField('Номер запроса', validators=[DataRequired()])
submit = SubmitField('Принять запрос')
class DeleteForm(FlaskForm):
submit = SubmitField('Удалить профиль')
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired()])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
remember_me = BooleanField('Запомнить меня')
submit = SubmitField('Отправить')
class ProfileForm(FlaskForm):
submit = SubmitField('Опубликовать профиль')
class RegisterForm(FlaskForm):
email = StringField('Email', validators=[DataRequired()])
name = StringField('Имя', validators=[DataRequired()])
surname = StringField('Фамилия', validators=[DataRequired()])
age = StringField('Возраст', validators=[DataRequired()])
country = SelectField('Страна', choices=[
('Не задана', 'Не задана'),
('Россия', 'Россия'),
('США', 'США'),
('Германия', 'Германия'),
('Китай', 'Китай')
], default='Не задана')
sex = RadioField('Пол', choices=[('м', 'Мужской'), ('ж', 'Женский')], default='м')
bio = TextAreaField('О себе', validators=[DataRequired()])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
repeat_passw = PasswordField('<PASSWORD>', validators=[DataRequired()])
submit = SubmitField('Отправить')
class RequestForm(FlaskForm):
profile_id = StringField('ID профиля', validators=[DataRequired()])
submit = SubmitField('Отправить запрос')
class NotesForm(FlaskForm):
header = StringField('Заголовок', validators=[DataRequired()])
note = TextAreaField('Запись', validators=[DataRequired()])
submit = SubmitField('Добавить запись')
class ParametersForm(FlaskForm):
age_from = StringField('Возраст от...')
age_to = StringField('Возраст до...')
country = SelectField('Страна', choices=[
('Не задана', 'Не задана'),
('Россия', 'Россия'),
('США', 'США'),
('Германия', 'Германия'),
('Китай', 'Китай')
], default='Не задана')
submit = SubmitField('Отсортировать')
<file_sep>/data/__all_models.py
from . import users
from . import profiles
from . import requests
from . import friends_db
from . import parameters
from . import notes<file_sep>/data/users.py
import sqlalchemy
from .db_session import SqlAlchemyBase
from sqlalchemy import orm
from flask_login import UserMixin
class User(SqlAlchemyBase, UserMixin):
__tablename__ = 'users'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True)
name = sqlalchemy.Column(sqlalchemy.String)
surname = sqlalchemy.Column(sqlalchemy.String)
age = sqlalchemy.Column(sqlalchemy.Integer)
country = sqlalchemy.Column(sqlalchemy.String)
sex = sqlalchemy.Column(sqlalchemy.String)
password = sqlalchemy.Column(sqlalchemy.String)
email = sqlalchemy.Column(sqlalchemy.String, unique=True)
bio = sqlalchemy.Column(sqlalchemy.String)
photo = sqlalchemy.Column(sqlalchemy.String)
profiles = orm.relation("Profiles", back_populates='user')
parameters = orm.relation("Parameter", back_populates='user')
notes = orm.relation("Note", back_populates='user')
<file_sep>/README.md
Этот веб-ресурс предназначен для поиска космических попутчиков RussianSpaceTourist по всему миру.
Все пользователи, которые регистрируются на сайте должны общаться на русском языке, из какой бы страны они ни были, потому что сайт ориентирован на программу космического туризма, созданную в России.
Для пользователей есть возможность:
- зарегистрироваться
- указать свои анкетне данные, краткую биографию
- опубликовать свою анкету
- добавить других пользователей в друзья (после этого можно увидеть их e-mail и связаться с ними).
- создание собственных заметок
- получение заявок на добавление в друзья от других пользователей.
<file_sep>/data/friends_db.py
import sqlalchemy
from sqlalchemy import orm
from .db_session import SqlAlchemyBase
class Friends(SqlAlchemyBase):
__tablename__ = 'friends'
id = sqlalchemy.Column(sqlalchemy.Integer,
primary_key=True, autoincrement=True)
user_id = sqlalchemy.Column(sqlalchemy.Integer,
sqlalchemy.ForeignKey("users.id"))
friend_id = sqlalchemy.Column(sqlalchemy.Integer)
user = orm.relation('User')
<file_sep>/data/parameters.py
import sqlalchemy
from .db_session import SqlAlchemyBase
from sqlalchemy import orm
from flask_login import UserMixin
class Parameter(SqlAlchemyBase, UserMixin):
__tablename__ = 'parameters'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True)
user_id = sqlalchemy.Column(sqlalchemy.Integer,
sqlalchemy.ForeignKey("users.id"))
age_from = sqlalchemy.Column(sqlalchemy.Integer)
age_to = sqlalchemy.Column(sqlalchemy.Integer)
country = sqlalchemy.Column(sqlalchemy.String)
user = orm.relation('User')
<file_sep>/main.py
from flask import Flask, render_template, redirect
from forms1 import RegisterForm, LoginForm, ProfileForm, DeleteForm, \
NotesForm, ParametersForm, AddFriendsForm, RequestForm
from flask_login import LoginManager, login_user, logout_user, current_user
from data import db_session, users, profiles, requests, friends_db, parameters, notes
import os
db_session.global_init("db/friends.sqlite")
session = db_session.create_session()
app = Flask(__name__)
app.config['SECRET_KEY'] = 'yandexlyceum_secret_key'
login_manager = LoginManager()
login_manager.init_app(app)
def sort_profiles(parameter): # сортируем анкеты по праметрам
profiles_list_all = []
profiles_list = []
for profile in session.query(profiles.Profiles):
profiles_list_all.append([profile, session.query(users.User).filter(
users.User.id == profile.user_id).first()]) # получаем все анкеты
if not parameter: # если параметр сортировки не задан, то возвращаем полный список анкет
return profiles_list_all
for profile in profiles_list_all: # если параметр задан
user = profile[1]
if ((parameter.age_from == '' or int(user.age) >= int(parameter.age_from))
and (parameter.age_to == '' or int(user.age) <= int(parameter.age_to))
and (parameter.country == 'Не задана' or user.country == parameter.country)):
# and (parameter.sex == 'Любой' or user.sex == parameter.sex)):
profiles_list.append(user)
return profiles_list
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
form = RequestForm()
if current_user.is_authenticated: # проверим может ли быть установлен параметр поика
parameter = session.query(parameters.Parameter).filter(parameters.Parameter.user_id == current_user.id).first()
else:
parameter = ''
profiles_list = sort_profiles(parameter) # получаем список анкет, подходящих под параметры
if form.validate_on_submit(): # если запрос отправлен
request = requests.Requests()
if not current_user.is_authenticated: # не можем отправить запрос если не известен отправитель
return render_template('main.html', form=form,
title="Главная",
profs=profiles_list,
message="Запрос не может быть отправлен"
)
try: # пробуем получить анкету под введеным номером
user_recipient = session.query(profiles.Profiles).filter(
profiles.Profiles.id == form.profile_id.data).first().user_id
except AttributeError: # если не получается, значит анкеты не существует
return render_template('main.html', form=form,
title="Главная",
profs=profiles_list,
message="Такого профиля не существует")
if current_user.id != user_recipient: # проверяем, чтобы запрос не отправить самому себе
for request in session.query(requests.Requests):
if [request.user_sender, request.user_recipient] == [current_user.id,
user_recipient]: # если запрос уже отправлен
return render_template('main.html', form=form,
title="Главная",
profs=profiles_list,
message="Запрос уже отправлен")
for friend in session.query(friends_db.Friends).filter(friends_db.Friends.user_id == current_user.id):
if friend.friend_id == session.query(profiles.Profiles).filter(
profiles.Profiles.id == form.profile_id.data).first().user_id: # если уже в друзьях
return render_template('main.html', form=form,
title="Главная",
profs=profiles_list,
message="Пользователь уже в друзьях")
for request in session.query(requests.Requests).filter(requests.Requests.user_recipient == current_user.id):
if request.user_sender == session.query(profiles.Profiles).filter(
profiles.Profiles.id == form.profile_id.data).first().user_id:
# нам уже отправил запрос этот пользователь
return render_template('main.html', form=form,
title="Главная",
profs=profiles_list,
message="Проверь свои запросы")
request.user_sender = current_user.id
request.user_recipient = user_recipient
session.add(request)
session.commit()
return render_template('main.html', form=form,
title="Главная",
profs=profiles_list)
return render_template('main.html', form=form,
title="Главная",
profs=profiles_list,
message="Запрос не может быть отправлен"
)
return render_template('main.html', title='Главная',
profs=profiles_list, form=form)
@app.route('/friends/requests', methods=['GET', 'POST'])
def friends_requests(): # принять запрс в друзья
form = AddFriendsForm()
requests_list = []
for request in session.query(requests.Requests).filter(requests.Requests.user_recipient == current_user.id):
requests_list.append(
[request.id, session.query(users.User).filter(users.User.id == request.user_sender).first()])
# все запросы текущего пользователя
if form.validate_on_submit():
friend = friends_db.Friends()
friend.user_id = current_user.id
try: # проверяем есть ли анкета под таким номером
friend.friend_id = session.query(requests.Requests).filter(
requests.Requests.id == form.request_id.data).first().user_sender
except AttributeError:
return render_template('requests.html',
title="Запросы", form=form,
requests_list=requests_list, message='Запрос не существует')
session.add(friend)
session.delete(session.query(requests.Requests).filter(
requests.Requests.id == form.request_id.data).first()) # удаляем запрос
session.commit()
requests_list = [] # обновляем список запросов
for request in session.query(requests.Requests).filter(requests.Requests.user_recipient == current_user.id):
if type(request) != 'NoneType': # если не осталось запросов
requests_list.append(
[request.id, session.query(users.User).filter(users.User.id == request.user_sender).first()])
return render_template('requests.html',
title="Запросы", form=form,
requests_list=requests_list)
return render_template('requests.html',
title="Запросы", form=form,
requests_list=requests_list)
@app.route('/friends', methods=['GET', 'POST'])
def friends():
friends_list = []
form = ProfileForm()
form_delete = DeleteForm()
profs_list = []
if not current_user.is_authenticated:
return render_template('friends.html',
title="Друзья")
for friend in session.query(friends_db.Friends).filter(
friends_db.Friends.user_id == current_user.id): # список друзей
friends_list.append(session.query(users.User).filter(users.User.id == friend.friend_id).first())
for profile in session.query(profiles.Profiles):
profs_list.append(profile.user_id)
if form.validate_on_submit() and current_user.id not in profs_list: # если анкета не опубликована
profile = profiles.Profiles()
profile.user_id = current_user.id
session.add(profile)
session.commit()
profs_list = [] # обновляем список анкет
for profile in session.query(profiles.Profiles):
profs_list.append(profile.user_id)
elif form_delete.validate_on_submit() and current_user.id in profs_list: # если анкета опубликована
session.delete(session.query(profiles.Profiles).filter(profiles.Profiles.user_id == current_user.id).first())
session.commit()
profs_list = [] # обновляем список анкет
for profile in session.query(profiles.Profiles):
profs_list.append(profile.user_id)
return render_template('friends.html', form=form,
title="Друзья", profs=profs_list,
user_id=current_user.id, form_delete=form_delete,
friends=friends_list)
@app.route('/login', methods=['GET', 'POST'])
def sign_in(): # вход
form = LoginForm()
if form.validate_on_submit():
session = db_session.create_session()
user = session.query(users.User).filter(users.User.email == form.email.data).first()
if user and (user.password == form.password.data):
login_user(user, remember=form.remember_me.data)
return redirect("/")
return render_template('sign_in.html',
title="Вход",
message="Неправильный логин или пароль",
form=form)
return render_template('sign_in.html', form=form, title='Вход')
@app.route('/logout')
def logout(): # выход
logout_user()
return redirect("/")
@login_manager.user_loader
def load_user(user_id):
session = db_session.create_session()
return session.query(users.User).get(user_id)
@app.route('/register', methods=['GET', 'POST'])
def register(): # регистрация
form = RegisterForm()
if form.validate_on_submit():
user = users.User()
user.name = form.name.data
user.surname = form.surname.data
user.age = form.age.data
user.country = form.country.data
user.sex = form.sex.data
user.password = form.password.data
user.email = form.email.data
user.bio = form.bio.data
if session.query(users.User).filter(users.User.email == form.email.data).first():
return render_template('reg.html', form=form, title="Регистрация", message="Email уже зарегистрирован.")
if int(form.age.data) <= 0: # проверяем корректность возраста
return render_template('reg.html', form=form, title="Регистрация", message="Некорректный возраст.")
if len(form.password.data) < 4: # проверяем корректность пароля
return render_template('reg.html', form=form, title="Регистрация", message="Слишком короткий пароль")
if form.password.data != form.repeat_passw.data: # сравниваем пароли
return render_template('reg.html', form=form, message="Пароли должны совпадать!", title="Регистрация")
else:
session.add(user)
session.commit()
return render_template('reg.html', form=form, message="Регистрация успешна!", title="Регистрация")
else:
return render_template('reg.html', form=form, title="Регистрация")
@app.route('/notes', methods=['GET', 'POST'])
def notes_func(): # добавляем заметки
form = NotesForm()
notes_list = []
if current_user.is_authenticated:
for note in session.query(notes.Note).filter(notes.Note.user_id == current_user.id):
notes_list.append(note) # заметки текущего пользователя
if form.validate_on_submit():
note = notes.Note()
note.user_id = current_user.id
note.header = form.header.data
note.note = form.note.data
session.add(note)
session.commit()
notes_list = [] # обновляем список заметок
for note in session.query(notes.Note).filter(notes.Note.user_id == current_user.id):
notes_list.append(note)
return render_template('notes.html', title="Заметки", form=form,
notes=notes_list)
@app.route('/parameters', methods=['GET', 'POST'])
def parameters_func(): # ставим параметры поиска
form = ParametersForm()
if form.validate_on_submit():
if ((form.age_from.data and int(form.age_from.data) <= 0)
or (form.age_to.data and int(form.age_to.data) <= 0)
or (form.age_from.data and form.age_to.data and
int(form.age_from.data) > int(form.age_to.data))):
return render_template('parameters.html', title="Поиск",
form=form, message='Некорректный возраст') # проверяем возраст на корректность
for parameter in session.query(parameters.Parameter).filter(parameters.Parameter.user_id == current_user.id):
session.delete(parameter) # очищаем бд с параметрами, чтобы не было накладок
parameter = parameters.Parameter()
parameter.user_id = current_user.id
parameter.age_from = form.age_from.data
parameter.age_to = form.age_to.data
parameter.country = form.country.data
parameter.sex = form.sex.data
session.add(parameter)
session.commit()
return render_template('parameters.html', title="Поиск по параметрам",
form=form)
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(port=port, host='0.0.0.0')
# app.run(port=8083, host='127.0.0.1', debug=True)
|
dc50ad45456676e394887e0ad5953cd34704f9c2
|
[
"Markdown",
"Python"
] | 7
|
Python
|
SheferSA/space-web
|
d5b949bd6b61948f5e3ef3b835e5bbb03644ac52
|
1292da76fb198b6d8e20d0f09c2ce44d5428eead
|
refs/heads/master
|
<file_sep>import { Matrix4 } from "./Geometry/Matrix4";
import { Point3 } from "./Geometry/Point3";
import { Vector3 } from "./Geometry/Vector3";
export interface Camera {
farClipPlane: number;
nearClipPlane: number;
pitch: number;
position: Point3;
verticalFieldOfView: number;
yaw: number;
}
export const getProjection = (
camera: Camera,
targetWidth: number,
targetHeight: number
): Matrix4 => {
const { farClipPlane, nearClipPlane, verticalFieldOfView } = camera;
return Matrix4.perspective(
verticalFieldOfView,
targetWidth,
targetHeight,
nearClipPlane,
farClipPlane
);
};
export const getView = (camera: Camera): Matrix4 => {
const { pitch, position, yaw } = camera;
return Matrix4.turnRh(position, yaw, pitch, Vector3.unitZ());
};
<file_sep>export class Trivector3 {
xyz: number;
constructor(xyz: number = 0) {
this.xyz = xyz;
}
}
<file_sep>import { Color } from "../Color";
import { Pipeline } from "./Pipeline";
import { GloBuffer } from "./GloBuffer";
export interface ClearAction {
color?: ClearColorAction;
depth?: ClearDepthAction;
stencil?: ClearStencilAction;
}
export interface ClearColorAction {
shouldClear: boolean;
value?: Color;
}
export interface ClearDepthAction {
shouldClear: boolean;
value?: number;
}
export interface ClearState {
color: Color;
depth: number;
stencil: number;
}
export interface ClearStencilAction {
shouldClear: boolean;
value?: number;
}
export interface DrawAction {
indexBuffer?: GloBuffer;
indicesCount: number;
startIndex: number;
vertexBuffers: GloBuffer[];
}
export interface Extensions {
depthTexture: WEBGL_depth_texture;
drawBuffers: WEBGL_draw_buffers;
floatTexture: OES_texture_float;
}
export interface GloContext {
extensions: Extensions;
gl: WebGLRenderingContext;
state: {
clear: ClearState;
pipeline: Pipeline | null;
};
}
export const clearTarget = (context: GloContext, action: ClearAction) => {
const { gl } = context;
const clearState = context.state.clear;
let mask = 0;
const { color, depth, stencil } = action;
if (color) {
const value = color.value;
if (value && !Color.isExactlyEqual(value, clearState.color)) {
gl.clearColor(value.r, value.g, value.b, value.a);
clearState.color = value;
}
mask |= gl.COLOR_BUFFER_BIT;
}
if (depth) {
const value = depth.value;
if (value && value !== clearState.depth) {
gl.clearDepth(value);
clearState.depth = value;
}
mask |= gl.DEPTH_BUFFER_BIT;
}
if (stencil) {
const value = stencil.value;
if (value && value !== clearState.stencil) {
gl.clearStencil(value);
clearState.stencil = value;
}
mask |= gl.STENCIL_BUFFER_BIT;
}
gl.clear(mask);
};
export const createContext = (canvas: HTMLCanvasElement): GloContext => {
const gl = canvas.getContext("webgl");
if (!gl) {
throw new Error("WebGL context could not be created.");
}
return {
extensions: createExtensions(gl),
gl,
state: {
clear: {
color: Color.transparentBlack(),
depth: 1,
stencil: 0,
},
pipeline: null,
},
};
};
export const draw = (context: GloContext, action: DrawAction) => {
const { gl } = context;
const { pipeline } = context.state;
if (!pipeline) {
throw new Error("No pipeline set before a draw.");
}
const { indexType, primitiveTopology } = pipeline.inputAssembly;
const { attributes } = pipeline.vertexLayout;
const { indexBuffer, indicesCount, vertexBuffers } = action;
for (const attribute of attributes) {
const {
componentCount,
isNormalized,
location,
offset,
stride,
type,
} = attribute;
const buffer = vertexBuffers[attribute.bufferIndex];
gl.bindBuffer(gl.ARRAY_BUFFER, buffer.handle);
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(
location,
componentCount,
type,
isNormalized,
stride,
offset
);
}
if (indexType === null) {
gl.drawArrays(primitiveTopology, 0, indicesCount);
} else {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer.handle);
gl.drawElements(primitiveTopology, indicesCount, indexType, 0);
}
};
const createExtensions = (gl: WebGLRenderingContext): Extensions => {
const depthTextureExtension = gl.getExtension("WEBGL_depth_texture");
if (!depthTextureExtension) {
throw new Error(
"The WebGL extension WEBGL_depth_texture is not supported."
);
}
const drawBuffersExtension = gl.getExtension("WEBGL_draw_buffers");
if (!drawBuffersExtension) {
throw new Error(`The WebGL extension WEBGL_draw_buffers is not supported.`);
}
const floatTextureExtension = gl.getExtension("OES_texture_float");
if (!floatTextureExtension) {
throw new Error("The WebGL extension OES_texture_float is not supported.");
}
return {
depthTexture: depthTextureExtension,
drawBuffers: drawBuffersExtension,
floatTexture: floatTextureExtension,
};
};
<file_sep>import { Vector3 } from "./Vector3";
export class Vector4 {
elements: number[];
constructor(elements: number[] = [0, 0, 0, 0]) {
this.elements = elements;
}
get x(): number {
return this.elements[0];
}
get y(): number {
return this.elements[1];
}
get z(): number {
return this.elements[2];
}
get w(): number {
return this.elements[3];
}
set x(x: number) {
this.elements[0] = x;
}
set y(y: number) {
this.elements[1] = y;
}
set z(z: number) {
this.elements[2] = z;
}
set w(w: number) {
this.elements[3] = w;
}
toString(): string {
return `⟨${this.x}, ${this.y}, ${this.z}, ${this.w}⟩`;
}
static dot(a: Vector4, b: Vector4): number {
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
static fromVector3(v: Vector3): Vector4 {
return new Vector4([v.x, v.y, v.z, 0]);
}
static unitX(): Vector4 {
return new Vector4([1, 0, 0, 0]);
}
static unitY(): Vector4 {
return new Vector4([0, 1, 0, 0]);
}
static unitZ(): Vector4 {
return new Vector4([0, 0, 1, 0]);
}
static unitW(): Vector4 {
return new Vector4([0, 0, 0, 1]);
}
}
<file_sep>import { GloContext } from "./GloContext";
export interface Viewport {
bottomLeftX: number;
bottomLeftY: number;
farPlane: number;
height: number;
nearPlane: number;
width: number;
}
export const setViewport = (context: GloContext, viewport: Viewport): void => {
const { gl } = context;
const {
bottomLeftX,
bottomLeftY,
farPlane,
height,
nearPlane,
width,
} = viewport;
gl.viewport(bottomLeftX, bottomLeftY, width, height);
gl.depthRange(nearPlane, farPlane);
};
<file_sep>import { Color } from "./Color";
import { Point3 } from "./Geometry/Point3";
import { Size3 } from "./Size3";
import { Rotor3 } from "./Geometry/Rotor3";
export interface Cuboid {
center: Point3;
orientation: Rotor3;
size: Size3;
style: SurfaceStyle;
type: "CUBOID";
}
export interface CuboidSpec {
center: Point3;
orientation?: Rotor3;
size: Size3;
style: SurfaceStyle;
}
export interface LineSegment {
endpoints: [Point3, Point3];
style: LineStyle;
type: "LINE_SEGMENT";
}
export interface LineSegmentSpec {
endpoints: [Point3, Point3];
style: LineStyle;
}
export interface LineStyle {
color: Color;
}
export type Primitive = Cuboid | LineSegment | Sphere;
export interface PrimitiveContext {
primitives: Primitive[];
}
export interface Sphere {
center: Point3;
radius: number;
style: SurfaceStyle;
type: "SPHERE";
}
export interface SphereSpec {
center: Point3;
radius: number;
style: SurfaceStyle;
}
export interface SurfaceStyle {
color: Color;
}
export const addCuboid = (context: PrimitiveContext, spec: CuboidSpec) => {
const { center, orientation, size, style } = spec;
const cuboid: Cuboid = {
center,
orientation: orientation || Rotor3.identity(),
size,
style,
type: "CUBOID",
};
context.primitives.push(cuboid);
};
export const addLineSegment = (
context: PrimitiveContext,
spec: LineSegmentSpec
) => {
const { endpoints, style } = spec;
const lineSegment: LineSegment = {
endpoints,
style,
type: "LINE_SEGMENT",
};
context.primitives.push(lineSegment);
};
export const addSphere = (context: PrimitiveContext, spec: SphereSpec) => {
const { center, radius, style } = spec;
const sphere: Sphere = {
center,
radius,
style,
type: "SPHERE",
};
context.primitives.push(sphere);
};
export const createPrimitiveContext = (): PrimitiveContext => {
return {
primitives: [],
};
};
export const getIndexCount = (primitive: Primitive) => {
switch (primitive.type) {
case "CUBOID": {
const sideCount = 6;
const indicesPerSide = 6;
return indicesPerSide * sideCount;
}
case "LINE_SEGMENT":
return 2;
case "SPHERE": {
const meridianCount = 10;
const parallelCount = 6;
const bandCount = parallelCount - 1;
return 6 * (meridianCount * bandCount + meridianCount);
}
}
};
export const getVertexCount = (primitive: Primitive) => {
switch (primitive.type) {
case "CUBOID": {
const sideCount = 6;
const verticesPerSide = 4;
return verticesPerSide * sideCount;
}
case "LINE_SEGMENT":
return 2;
case "SPHERE": {
const meridianCount = 10;
const parallelCount = 6;
const poleVertexCount = 2;
return meridianCount * parallelCount + poleVertexCount;
}
}
};
export const resetPrimitives = (context: PrimitiveContext) => {
context.primitives = [];
};
<file_sep>Dawn Toolbox
============
A test app for math
<file_sep>import { GloContext } from "./GloContext";
import { Size2 } from "../Size2";
export type PixelFormat =
| "RGBA8"
| "RGBA32F"
| "RGB8"
| "RGB32F"
| "RG8"
| "RG32F"
| "R8"
| "R32F"
| "DEPTH16"
| "DEPTH24"
| "DEPTH24_STENCIL8";
export type SamplerAddressMode = "CLAMP_TO_EDGE" | "MIRRORED_REPEAT" | "REPEAT";
export type SamplerFilter = "LINEAR" | "POINT";
export interface SamplerSpec {
addressModeU: SamplerAddressMode;
addressModeV: SamplerAddressMode;
magnifyFilter: SamplerFilter;
minifyFilter: SamplerFilter;
mipmapFilter: SamplerFilter;
}
export interface Texture {
handle: WebGLTexture;
internalFormat: GLenum;
size: Size2;
type: TextureType;
}
export interface TextureContent {
pixelFormat: PixelFormat;
subimagesByCubeFaceAndMipLevel: TextureSubimage[][];
}
export interface TextureSpec {
content?: TextureContent;
generateMipmaps: boolean;
pixelFormat: PixelFormat;
sampler: SamplerSpec;
size: Size2;
type: TextureType;
}
export interface TextureSubimage {
pixels: ArrayBufferView;
}
export type TextureType = "2D" | "CUBE";
export const bind = (
context: GloContext,
texture: Texture,
activeTexture: number
) => {
const { gl } = context;
const { handle, type } = texture;
const target = getTextureTypeTarget(context, type);
gl.activeTexture(gl.TEXTURE0 + activeTexture);
gl.bindTexture(target, handle);
};
export const createTexture = (
context: GloContext,
spec: TextureSpec
): Texture => {
const { gl } = context;
const { pixelFormat, sampler, type } = spec;
const content = spec.content ? spec.content : null;
const genericFormat = getPixelFormatGenericFormat(context, pixelFormat);
const internalFormat = getPixelFormatInternalFormat(context, pixelFormat);
const minifyFilter = getSamplerFilter(
context,
sampler.minifyFilter,
sampler.mipmapFilter
);
const magnifyFilter = getSamplerFilter(
context,
sampler.magnifyFilter,
sampler.mipmapFilter
);
const addressModeU = getSamplerAddressMode(context, sampler.addressModeU);
const addressModeV = getSamplerAddressMode(context, sampler.addressModeV);
const size = spec.size;
const formatType = spec.content
? getPixelFormatType(context, spec.content.pixelFormat)
: getPixelFormatType(context, pixelFormat);
const target = getTextureTypeTarget(context, type);
const texture = gl.createTexture();
gl.bindTexture(target, texture);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, minifyFilter);
gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, magnifyFilter);
gl.texParameteri(target, gl.TEXTURE_WRAP_S, addressModeU);
gl.texParameteri(target, gl.TEXTURE_WRAP_T, addressModeV);
const cubeFaceCount = getTextureTypeCubeFaceCount(type);
for (let cubeFace = 0; cubeFace < cubeFaceCount; cubeFace++) {
const subimageTarget = getTextureTypeSubimageTarget(
context,
type,
cubeFace
);
const subimagesByMipLevel =
content.subimagesByCubeFaceAndMipLevel[cubeFace];
for (let mipLevel = 0; mipLevel < subimagesByMipLevel.length; mipLevel++) {
const subimage = subimagesByMipLevel[mipLevel];
const width = Math.max(size.width >> mipLevel, 1);
const height = Math.max(size.height >> mipLevel, 1);
gl.texImage2D(
subimageTarget,
mipLevel,
internalFormat,
width,
height,
0,
genericFormat,
formatType,
subimage.pixels
);
}
}
if (spec.generateMipmaps) {
gl.generateMipmap(gl.TEXTURE_2D);
}
return {
handle: texture,
internalFormat,
size,
type,
};
};
const getPixelFormatGenericFormat = (
context: GloContext,
pixelFormat: PixelFormat
): GLenum => {
const { gl } = context;
switch (pixelFormat) {
case "RGBA8":
return gl.RGBA;
case "RGB8":
return gl.RGB;
case "RG8":
return gl.LUMINANCE_ALPHA;
case "R8":
return gl.LUMINANCE;
case "DEPTH16":
case "DEPTH24":
return gl.DEPTH_COMPONENT;
case "DEPTH24_STENCIL8":
return gl.DEPTH_STENCIL;
case "RGBA32F":
case "RGB32F":
case "RG32F":
case "R32F":
return gl.FLOAT;
default:
throw new Error(`Pixel format of type ${pixelFormat} is unknown`);
}
};
const getPixelFormatInternalFormat = (
context: GloContext,
pixelFormat: PixelFormat
): GLenum => {
const { gl } = context;
switch (pixelFormat) {
case "RGBA8":
return gl.RGBA;
case "RGB8":
return gl.RGB;
case "RG8":
return gl.LUMINANCE_ALPHA;
case "R8":
return gl.LUMINANCE;
case "DEPTH16":
case "DEPTH24":
return gl.DEPTH_COMPONENT;
case "DEPTH24_STENCIL8":
return gl.DEPTH_STENCIL;
case "RGBA32F":
case "RGB32F":
case "RG32F":
case "R32F":
throw new Error(
`Pixel format of type ${pixelFormat} is unsupported as an internal format.`
);
default:
throw new Error(`Pixel format of type ${pixelFormat} is unknown`);
}
};
const getPixelFormatType = (
context: GloContext,
pixelFormat: PixelFormat
): GLenum => {
const { gl } = context;
const depthTexture = context.extensions.depthTexture;
switch (pixelFormat) {
case "RGBA8":
case "RGB8":
case "RG8":
case "R8":
return gl.UNSIGNED_BYTE;
case "RGBA32F":
case "RGB32F":
case "RG32F":
case "R32F":
return gl.FLOAT;
case "DEPTH16":
return gl.UNSIGNED_SHORT;
case "DEPTH24":
return gl.UNSIGNED_INT;
case "DEPTH24_STENCIL8":
return depthTexture.UNSIGNED_INT_24_8_WEBGL;
default:
throw new Error(`Pixel format of type ${pixelFormat} is unknown.`);
}
};
const getSamplerAddressMode = (
context: GloContext,
samplerAddressMode: SamplerAddressMode
): GLenum => {
const { gl } = context;
switch (samplerAddressMode) {
case "CLAMP_TO_EDGE":
return gl.CLAMP_TO_EDGE;
case "MIRRORED_REPEAT":
return gl.MIRRORED_REPEAT;
case "REPEAT":
return gl.REPEAT;
default:
throw new Error(
`Sampler address mode of type ${samplerAddressMode} is unknown.`
);
}
};
const getSamplerFilter = (
context: GloContext,
filter: SamplerFilter,
mipmapFilter: SamplerFilter
): GLenum => {
const { gl } = context;
switch (filter) {
case "LINEAR":
switch (mipmapFilter) {
case "LINEAR":
return gl.LINEAR_MIPMAP_LINEAR;
case "POINT":
return gl.LINEAR_MIPMAP_NEAREST;
default:
throw new Error(`Sampler filter of type ${filter} is unknown.`);
}
case "POINT":
switch (mipmapFilter) {
case "LINEAR":
return gl.NEAREST_MIPMAP_LINEAR;
case "POINT":
return gl.NEAREST_MIPMAP_NEAREST;
default:
throw new Error(`Sampler filter of type ${filter} is unknown.`);
}
default:
throw new Error(`Sampler filter of type ${filter} is unknown.`);
}
};
const getTextureTypeCubeFaceCount = (textureType: TextureType): number => {
switch (textureType) {
case "2D":
return 1;
case "CUBE":
return 6;
default:
throw new Error(`Texture type of type ${textureType} is unknown.`);
}
};
const getTextureTypeSubimageTarget = (
context: GloContext,
textureType: TextureType,
cubeFace: number
): GLenum => {
const { gl } = context;
switch (textureType) {
case "2D":
return gl.TEXTURE_2D;
case "CUBE":
switch (cubeFace) {
case 0:
return gl.TEXTURE_CUBE_MAP_POSITIVE_X;
case 1:
return gl.TEXTURE_CUBE_MAP_NEGATIVE_X;
case 2:
return gl.TEXTURE_CUBE_MAP_POSITIVE_Y;
case 3:
return gl.TEXTURE_CUBE_MAP_NEGATIVE_Y;
case 4:
return gl.TEXTURE_CUBE_MAP_POSITIVE_Z;
case 5:
return gl.TEXTURE_CUBE_MAP_NEGATIVE_Z;
default:
throw new Error(`Cube face of index ${cubeFace} is invalid.`);
}
default:
throw new Error(`Texture type of type ${textureType} is unknown.`);
}
};
const getTextureTypeTarget = (
context: GloContext,
textureType: TextureType
): GLenum => {
const { gl } = context;
switch (textureType) {
case "2D":
return gl.TEXTURE_2D;
case "CUBE":
return gl.TEXTURE_CUBE_MAP;
default:
throw new Error(`Texture type of type ${textureType} is unknown.`);
}
};
<file_sep>import { Bivector2 } from "./Bivector2";
import { Bivector3 } from "./Bivector3";
import { Rotor3 } from "./Rotor3";
import { Trivector3 } from "./Trivector3";
import { Vector2 } from "./Vector2";
import { Vector3 } from "./Vector3";
export const biWedge = (a: Bivector3, b: Vector3): Trivector3 => {
return new Trivector3(-a.yz * b.x + a.xz * b.y - a.xy * b.z);
};
export const rotate = (rotor: Rotor3, vector: Vector3): Vector3 => {
const q = new Vector3([
rotor.a * vector.x + rotor.b.xy * vector.y + rotor.b.xz * vector.z,
rotor.a * vector.y - rotor.b.xy * vector.x + rotor.b.yz * vector.z,
rotor.a * vector.z - rotor.b.xz * vector.x - rotor.b.yz * vector.y,
]);
const w = biWedge(rotor.b, vector);
return new Vector3([
rotor.a * q.x + rotor.b.xy * q.y + rotor.b.xz * q.z - rotor.b.yz * w.xyz,
rotor.a * q.y - rotor.b.xy * q.x + rotor.b.xz * w.xyz + rotor.b.yz * q.z,
rotor.a * q.z - rotor.b.xy * w.xyz - rotor.b.xz * q.x - rotor.b.yz * q.y,
]);
};
export const wedge = (a: Vector3, b: Vector3): Bivector3 => {
return new Bivector3([
a.x * b.y - a.y * b.x,
a.x * b.z - a.z * b.x,
a.y * b.z - a.z * b.y,
]);
};
export const wedge2 = (a: Vector2, b: Vector2): Bivector2 => {
return new Bivector2(a.x * b.y - a.y * b.x);
};
<file_sep>import { times } from "./Array";
import {
BinaryReader,
createBinaryReader,
expect,
expectBytesLeft,
expectIndexInBounds,
haveReachedEndOfFile,
readFloat32Array,
readString,
readUint16,
readUint16Array,
readUint32,
readUint8,
skipBytes,
} from "./BinaryReader";
import { Point3 } from "./Geometry/Point3";
import { Quaternion } from "./Geometry/Quaternion";
import { Rotor3 } from "./Geometry/Rotor3";
import { Vector3 } from "./Geometry/Vector3";
import { TraceError } from "./TraceError";
const FILE_HEADER_TAG = "DWNSCENE";
const FILE_VERSION = 1;
export interface Accessor {
buffer: ArrayBuffer;
byteCount: number;
byteIndex: number;
byteStride: number;
componentCount: number;
componentType: ComponentType;
}
interface AccessorSpec {
bufferIndex: number;
byteCount: number;
byteIndex: number;
byteStride: number;
componentCount: number;
componentType: ComponentType;
}
enum ChunkType {
Accessor = "ACCE",
Buffer = "BUFF",
Mesh = "MESH",
Object = "OBJE",
TransformNode = "TRAN",
VertexLayout = "VERT",
}
interface ChunkHeader {
tag: string;
byteCount: number;
}
export enum ComponentType {
Invalid,
Float32,
Int8,
Int16,
Int32,
Uint8,
Uint16,
Uint32,
}
interface FileHeader {
tag: string;
version: number;
byteCount: number;
}
export interface Mesh {
indexAccessor: Accessor;
vertexLayout: VertexLayout;
}
export interface MeshObject {
mesh: Mesh;
type: ObjectType.Mesh;
}
interface MeshSpec {
indexAccessorIndex: number;
materialIndex: number;
vertexLayoutIndex: number;
}
export type Object = MeshObject;
interface ObjectSpec {
contentIndex: number;
type: ObjectType;
}
export enum ObjectType {
Invalid,
Mesh,
}
export interface Scene {
buffers: ArrayBuffer[];
meshes: Mesh[];
rootTransformNodes: TransformNode[];
transformNodes: TransformNode[];
}
export interface Transform {
orientation: Rotor3;
position: Point3;
scale: Vector3;
}
export interface TransformNode {
children: TransformNode[];
object: Object;
parent: TransformNode | null;
transform: Transform;
}
interface TransformNodeSpec {
childIndices: number[];
objectIndex: number;
transform: Transform;
}
export interface VertexAttribute {
accessor: Accessor;
type: VertexAttributeType;
}
interface VertexAttributeSpec {
accessorIndex: number;
type: VertexAttributeType;
}
export enum VertexAttributeType {
Invalid,
Color,
Normal,
Position,
Texcoord,
}
export interface VertexLayout {
vertexAttributes: VertexAttribute[];
}
interface VertexLayoutSpec {
vertexAttributes: VertexAttributeSpec[];
}
export const deserialize = (sourceData: ArrayBuffer): Scene => {
const reader = createBinaryReader(sourceData);
readFileHeader(reader);
let accessorSpecs: AccessorSpec[] = [];
let buffers: ArrayBuffer[] = [];
let meshSpecs: MeshSpec[] = [];
let objectSpecs: ObjectSpec[] = [];
let transformNodeSpecs: TransformNodeSpec[] = [];
let vertexLayoutSpecs: VertexLayoutSpec[] = [];
while (!haveReachedEndOfFile(reader)) {
const chunkHeader = readChunkHeader(reader);
switch (chunkHeader.tag) {
case ChunkType.Accessor:
accessorSpecs = readAccessorChunk(reader, chunkHeader);
break;
case ChunkType.Buffer:
buffers = readBufferChunk(reader);
break;
case ChunkType.Mesh:
meshSpecs = readMeshChunk(reader, chunkHeader);
break;
case ChunkType.Object:
objectSpecs = readObjectChunk(reader, chunkHeader);
break;
case ChunkType.TransformNode:
transformNodeSpecs = readTransformNodeChunk(reader);
break;
case ChunkType.VertexLayout:
vertexLayoutSpecs = readVertexLayoutChunk(reader);
break;
default:
skipBytes(reader, chunkHeader.byteCount);
break;
}
}
const accessors = accessorSpecs.map((spec) => createAccessor(spec, buffers));
const vertexLayouts = vertexLayoutSpecs.map((spec) =>
createVertexLayout(spec, accessors)
);
const meshes = meshSpecs.map((spec) =>
createMesh(spec, vertexLayouts, accessors)
);
const objects = objectSpecs.map((spec) => createObject(spec, meshes));
const transformNodes = transformNodeSpecs.map((spec) =>
createTransformNodeWithoutChildren(spec, objects)
);
resolveTransformNodeConnections(transformNodeSpecs, transformNodes);
const rootTransformNodes = transformNodes.filter(
(transformNode) => !transformNode.parent
);
return {
buffers,
meshes,
rootTransformNodes,
transformNodes,
};
};
export const getElementCount = (accessor: Accessor): number => {
const { byteCount, byteStride } = accessor;
return byteCount / byteStride;
};
const createAccessor = (
spec: AccessorSpec,
buffers: ArrayBuffer[]
): Accessor => {
const {
bufferIndex,
byteCount,
byteIndex,
byteStride,
componentCount,
componentType,
} = spec;
expectIndexInBounds(bufferIndex, buffers, "Buffer index is out of bounds.");
const buffer = buffers[bufferIndex];
return {
buffer,
byteCount,
byteIndex,
byteStride,
componentCount,
componentType,
};
};
const createMesh = (
spec: MeshSpec,
vertexLayouts: VertexLayout[],
accessors: Accessor[]
): Mesh => {
const { indexAccessorIndex, vertexLayoutIndex } = spec;
expectIndexInBounds(
indexAccessorIndex,
accessors,
"Index accessor index is out of bounds."
);
expectIndexInBounds(
vertexLayoutIndex,
vertexLayouts,
"Vertex layout index is out of bounds."
);
const indexAccessor = accessors[indexAccessorIndex];
const vertexLayout = vertexLayouts[vertexLayoutIndex];
return {
indexAccessor,
vertexLayout,
};
};
const createObject = (spec: ObjectSpec, meshes: Mesh[]): Object => {
const { contentIndex, type } = spec;
switch (type) {
case ObjectType.Mesh: {
expectIndexInBounds(contentIndex, meshes, "Mesh index is out of bounds.");
const mesh = meshes[contentIndex];
return {
mesh,
type,
};
}
default:
throw new Error("Object type is invalid.");
}
};
const createTransformNodeWithoutChildren = (
spec: TransformNodeSpec,
objects: Object[]
): TransformNode => {
const { objectIndex, transform } = spec;
expectIndexInBounds(objectIndex, objects, "Object index is out of bounds.");
const object = objects[objectIndex];
return {
children: [],
object,
parent: null,
transform,
};
};
const createVertexAttribute = (
spec: VertexAttributeSpec,
accessors: Accessor[]
): VertexAttribute => {
const { accessorIndex, type } = spec;
expectIndexInBounds(
accessorIndex,
accessors,
"Accessor index is out of bounds."
);
const accessor = accessors[accessorIndex];
return {
accessor,
type,
};
};
const createVertexLayout = (
spec: VertexLayoutSpec,
accessors: Accessor[]
): VertexLayout => {
const vertexAttributes = spec.vertexAttributes.map((vertexAttributeSpec) =>
createVertexAttribute(vertexAttributeSpec, accessors)
);
return {
vertexAttributes,
};
};
const isComponentType = (type: number): boolean => {
switch (type) {
case ComponentType.Float32:
case ComponentType.Int16:
case ComponentType.Int32:
case ComponentType.Int8:
case ComponentType.Uint16:
case ComponentType.Uint32:
case ComponentType.Uint8:
return true;
default:
return false;
}
};
const isObjectType = (type: number): boolean => {
switch (type) {
case ObjectType.Mesh:
return true;
default:
return false;
}
};
const isVertexAttributeType = (type: number): boolean => {
switch (type) {
case VertexAttributeType.Color:
case VertexAttributeType.Normal:
case VertexAttributeType.Position:
case VertexAttributeType.Texcoord:
return true;
default:
return false;
}
};
const readAccessorSpec = (reader: BinaryReader): AccessorSpec => {
const byteCount = readUint32(reader);
const byteIndex = readUint32(reader);
const byteStride = readUint16(reader);
const bufferIndex = readUint16(reader);
const componentCount = readUint8(reader);
const componentType = readUint8(reader);
expect(byteCount > 0, "Byte count must be nonzero.");
expect(byteStride > 0, "Stride must be nonzero.");
expect(componentCount > 0, "Component count must be nonzero.");
expect(
isComponentType(componentType),
`Value ${componentType} is not a valid vertex attribute component type.`
);
return {
bufferIndex,
byteCount,
byteIndex,
byteStride,
componentCount,
componentType,
};
};
const readAccessorChunk = (
reader: BinaryReader,
chunkHeader: ChunkHeader
): AccessorSpec[] => {
const bytesPerAccessor = 14;
const accessorCount = chunkHeader.byteCount / bytesPerAccessor;
expect(accessorCount > 0, "Accessor count must be nonzero.");
const accessors: AccessorSpec[] = [];
for (let i = 0; i < accessorCount; i++) {
const accessor = readAccessorSpec(reader);
accessors.push(accessor);
}
return accessors;
};
const readBuffer = (reader: BinaryReader): ArrayBuffer => {
const byteCount = readUint32(reader);
const buffer = reader.sourceData.slice(
reader.byteIndex,
reader.byteIndex + byteCount
);
skipBytes(reader, byteCount);
return buffer;
};
const readBufferChunk = (reader: BinaryReader): ArrayBuffer[] => {
const bufferCount = readUint16(reader);
expect(bufferCount > 0, "Buffer count must be nonzero.");
const buffers = times(bufferCount, () => readBuffer(reader));
return buffers;
};
const readChunkHeader = (reader: BinaryReader): ChunkHeader => {
try {
const tag = readString(reader, 4);
const byteCount = readUint32(reader);
return {
byteCount,
tag,
};
} catch (error) {
throw new TraceError(error, "Failed reading a chunk header.");
}
};
const readFileHeader = (reader: BinaryReader): FileHeader => {
try {
const tag = readString(reader, 8);
const version = readUint32(reader);
const byteCount = readUint32(reader);
expect(tag === FILE_HEADER_TAG, "Tag is not present.");
expect(version === FILE_VERSION, `Version ${version} is not supported.`);
expectBytesLeft(
reader,
byteCount,
"File size doesn't match the header file size."
);
return {
tag,
version,
byteCount,
};
} catch (error) {
throw new TraceError(error, "Failed reading the file header.");
}
};
const readMeshChunk = (
reader: BinaryReader,
chunkHeader: ChunkHeader
): MeshSpec[] => {
const bytesPerMesh = 6;
const meshCount = chunkHeader.byteCount / bytesPerMesh;
const meshes = times(meshCount, () => readMeshSpec(reader));
return meshes;
};
const readMeshSpec = (reader: BinaryReader): MeshSpec => {
const indexAccessorIndex = readUint16(reader);
const materialIndex = readUint16(reader);
const vertexLayoutIndex = readUint16(reader);
return {
indexAccessorIndex,
materialIndex,
vertexLayoutIndex,
};
};
const readObjectChunk = (
reader: BinaryReader,
chunkHeader: ChunkHeader
): ObjectSpec[] => {
const bytesPerObject = 3;
const objectCount = chunkHeader.byteCount / bytesPerObject;
expect(objectCount > 0, "Object count must be nonzero.");
const objectSpecs = times(objectCount, () => readObjectSpec(reader));
return objectSpecs;
};
const readObjectSpec = (reader: BinaryReader): ObjectSpec => {
const contentIndex = readUint16(reader);
const type = readUint8(reader);
expect(isObjectType(type), `Value ${type} is not a valid object type.`);
return {
contentIndex,
type,
};
};
const readTransformNodeChunk = (reader: BinaryReader): TransformNodeSpec[] => {
const transformNodeCount = readUint16(reader);
expect(transformNodeCount > 0, "Transform node count must be nonzero.");
const transformNodeSpecs = times(transformNodeCount, () =>
readTransformNodeSpec(reader)
);
return transformNodeSpecs;
};
const readTransformNodeSpec = (reader: BinaryReader): TransformNodeSpec => {
const orientationValues = readFloat32Array(reader, 4);
const positionValues = readFloat32Array(reader, 3);
const scaleValues = readFloat32Array(reader, 3);
const objectIndex = readUint16(reader);
const childIndexCount = readUint16(reader);
const childIndices = readUint16Array(reader, childIndexCount);
const transform: Transform = {
orientation: Rotor3.fromQuaternion(new Quaternion(orientationValues)),
position: new Point3(positionValues),
scale: new Vector3(scaleValues),
};
return {
childIndices,
objectIndex,
transform,
};
};
const readVertexAttributeSpec = (reader: BinaryReader): VertexAttributeSpec => {
const accessorIndex = readUint16(reader);
const type = readUint8(reader);
expect(
isVertexAttributeType(type),
`Value ${type} is not a valid vertex attribute type.`
);
return {
accessorIndex,
type,
};
};
const readVertexLayoutChunk = (reader: BinaryReader): VertexLayoutSpec[] => {
const vertexLayoutCount = readUint16(reader);
expect(vertexLayoutCount > 0, "Vertex layout count must be nonzero.");
const vertexLayouts = times(vertexLayoutCount, () =>
readVertexLayoutSpec(reader)
);
return vertexLayouts;
};
const readVertexLayoutSpec = (reader: BinaryReader): VertexLayoutSpec => {
const vertexAttributeCount = readUint16(reader);
expect(vertexAttributeCount > 0, "Vertex attribute count must be nonzero.");
const vertexAttributes = times(vertexAttributeCount, () =>
readVertexAttributeSpec(reader)
);
return {
vertexAttributes,
};
};
const resolveTransformNodeConnections = (
specs: TransformNodeSpec[],
transformNodes: TransformNode[]
) => {
for (let i = 0; i < transformNodes.length; i++) {
const spec = specs[i];
const transformNode = transformNodes[i];
transformNode.children = spec.childIndices.map((childIndex) => {
expectIndexInBounds(
childIndex,
transformNodes,
"Transform node child index is out of bounds."
);
const child = transformNodes[childIndex];
child.parent = transformNode;
return child;
});
}
};
<file_sep>import { ShaderProgram } from "./ShaderProgram";
import { GloContext } from "./GloContext";
export type CompareOp =
| "ALWAYS"
| "EQUAL"
| "GREATER"
| "GREATER_OR_EQUAL"
| "LESS"
| "LESS_OR_EQUAL"
| "NEVER"
| "NOT_EQUAL";
export type CullMode = "BACK" | "FRONT" | "NONE";
export interface DepthStencilState {
backStencil: StencilOpState;
depthCompareOp: GLenum;
frontStencil: StencilOpState;
shouldCompareDepth: boolean;
shouldWriteDepth: boolean;
shouldUseStencil: boolean;
}
export type DepthStencilStateSpec =
| DepthStencilStateSpecNoStencil
| DepthStencilStateSpecWithStencil;
interface DepthStencilStateSpecNoStencil {
depthCompareOp?: CompareOp;
shouldCompareDepth: boolean;
shouldWriteDepth: boolean;
shouldUseStencil: false;
}
interface DepthStencilStateSpecWithStencil {
backStencil: StencilOpStateSpec;
depthCompareOp: CompareOp;
frontStencil: StencilOpStateSpec;
shouldCompareDepth: boolean;
shouldWriteDepth: boolean;
shouldUseStencil: true;
}
export type FaceWinding = "CLOCKWISE" | "COUNTERCLOCKWISE";
export type IndexType = "NONE" | "UINT16" | "UINT32";
export interface InputAssembly {
bytesPerIndex: number;
indexType: GLenum | null;
primitiveTopology: GLenum;
}
export interface InputAssemblySpec {
indexType: IndexType;
primitiveTopology: PrimitiveTopology;
}
export interface Pipeline {
depthStencil: DepthStencilState;
inputAssembly: InputAssembly;
rasterizer: RasterizerState;
shader: ShaderProgram;
vertexLayout: VertexLayout;
}
export interface PipelineSpec {
depthStencil: DepthStencilStateSpec;
inputAssembly: InputAssemblySpec;
rasterizer?: RasterizerStateSpec;
shader: ShaderProgram;
vertexLayout: VertexLayoutSpec;
}
export type PrimitiveTopology = "LINE_LIST" | "TRIANGLE_LIST";
export interface RasterizerState {
cullMode: GLenum;
depthBias: RasterizerStateDepthBias;
faceWinding: GLenum;
shouldUseDepthBias: boolean;
}
interface RasterizerStateDepthBias {
clamp: number;
constant: number;
slope: number;
}
interface RasterizerStateSpecDepthBias {
clamp: number;
constant: number;
slope: number;
}
export type RasterizerStateSpec =
| RasterizerStateSpecWithDepthBias
| RasterizerStateSpecWithoutDepthBias;
interface RasterizerStateSpecWithDepthBias {
cullMode?: CullMode;
depthBias: RasterizerStateSpecDepthBias;
faceWinding?: FaceWinding;
shouldUseDepthBias: true;
}
interface RasterizerStateSpecWithoutDepthBias {
cullMode?: CullMode;
faceWinding?: FaceWinding;
shouldUseDepthBias: false | undefined;
}
export type StencilOp =
| "DECREMENT_AND_CLAMP"
| "DECREMENT_AND_WRAP"
| "INCREMENT_AND_CLAMP"
| "INCREMENT_AND_WRAP"
| "INVERT"
| "KEEP"
| "REPLACE"
| "ZERO";
export interface StencilOpState {
compareMask: number;
compareOp: GLenum;
depthFailOp: GLenum;
failOp: GLenum;
passOp: GLenum;
reference: number;
writeMask: number;
}
export interface StencilOpStateSpec {
compareMask: number;
compareOp: CompareOp;
depthFailOp: StencilOp;
failOp: StencilOp;
passOp: StencilOp;
reference: number;
writeMask: number;
}
export interface VertexAttribute {
bufferIndex: number;
componentCount: number;
isNormalized: boolean;
location: GLint | null;
offset: number;
stride: number;
type: GLenum;
}
export interface VertexAttributeSpec {
bufferIndex: number;
format: VertexFormat;
name: string;
}
export type VertexFormat =
| "FLOAT1"
| "FLOAT2"
| "FLOAT3"
| "FLOAT4"
| "SBYTE4_NORM"
| "UBYTE4_NORM"
| "USHORT2_NORM";
export interface VertexLayout {
attributes: VertexAttribute[];
}
export interface VertexLayoutSpec {
attributes: VertexAttributeSpec[];
}
export const createPipeline = (
context: GloContext,
spec: PipelineSpec
): Pipeline => {
const { shader } = spec;
const depthStencil = createDepthStencilState(context, spec.depthStencil);
const inputAssembly = createInputAssembly(context, spec.inputAssembly);
const rasterizer = createRasterizerState(context, spec.rasterizer);
const vertexLayout = createVertexLayout(context, spec.vertexLayout, shader);
return {
depthStencil,
inputAssembly,
rasterizer,
shader,
vertexLayout,
};
};
export const getBytesPerVertex = (
vertexLayout: VertexLayout,
bufferIndex: number
): number => {
const { attributes } = vertexLayout;
const foundAttribute = attributes.find(
attribute => attribute.bufferIndex === bufferIndex
);
return foundAttribute.stride;
};
export const getVertexFormatSize = (vertexFormat: VertexFormat): number => {
switch (vertexFormat) {
case "FLOAT1":
return 4;
case "FLOAT2":
return 8;
case "FLOAT3":
return 12;
case "FLOAT4":
return 16;
case "SBYTE4_NORM":
return 4;
case "UBYTE4_NORM":
return 4;
case "USHORT2_NORM":
return 4;
default:
throw new Error(`Vertex format of type ${vertexFormat} is unknown.`);
}
};
export const setPipeline = (context: GloContext, pipeline: Pipeline): void => {
const { gl, state } = context;
gl.useProgram(pipeline.shader.handle);
setDepthStencilState(context, pipeline.depthStencil);
setRasterizerState(context, pipeline.rasterizer);
state.pipeline = pipeline;
};
const createDepthStencilState = (
context: GloContext,
spec: DepthStencilStateSpec
): DepthStencilState => {
const { gl } = context;
const { shouldCompareDepth, shouldUseStencil, shouldWriteDepth } = spec;
const depthCompareOp = spec.depthCompareOp
? getCompareOp(context, spec.depthCompareOp)
: gl.LESS;
let backStencil;
let frontStencil;
if (spec.shouldUseStencil) {
backStencil = createStencilOpState(context, spec.backStencil);
frontStencil = createStencilOpState(context, spec.frontStencil);
} else {
backStencil = defaultStencilOpState(context);
frontStencil = defaultStencilOpState(context);
}
return {
backStencil,
depthCompareOp,
frontStencil,
shouldCompareDepth,
shouldUseStencil,
shouldWriteDepth,
};
};
const createInputAssembly = (
context: GloContext,
spec: InputAssemblySpec
): InputAssembly => {
const { indexType, primitiveTopology } = spec;
return {
bytesPerIndex: getBytesPerIndex(indexType),
indexType: getIndexType(context, indexType),
primitiveTopology: getPrimitiveTopology(context, primitiveTopology),
};
};
const createRasterizerState = (
context: GloContext,
spec?: RasterizerStateSpec
): RasterizerState => {
const cullMode = spec?.cullMode || "BACK";
const faceWinding = spec?.faceWinding || "COUNTERCLOCKWISE";
let depthBias: RasterizerStateDepthBias;
if (spec?.shouldUseDepthBias) {
depthBias = createRasterizerStateDepthBias(spec.depthBias);
} else {
depthBias = defaultRasterizerStateDepthBias();
}
return {
cullMode: getCullMode(context, cullMode),
depthBias,
faceWinding: getFaceWinding(context, faceWinding),
shouldUseDepthBias: spec && spec.shouldUseDepthBias,
};
};
const createRasterizerStateDepthBias = (
spec: RasterizerStateSpecDepthBias
): RasterizerStateDepthBias => {
const { clamp, constant, slope } = spec;
return {
clamp,
constant,
slope,
};
};
const createStencilOpState = (
context: GloContext,
spec: StencilOpStateSpec
): StencilOpState => {
const {
compareMask,
compareOp,
depthFailOp,
failOp,
passOp,
reference,
writeMask,
} = spec;
return {
compareMask,
compareOp: getCompareOp(context, compareOp),
depthFailOp: getStencilOp(context, depthFailOp),
failOp: getStencilOp(context, failOp),
passOp: getStencilOp(context, passOp),
reference,
writeMask,
};
};
const createVertexLayout = (
context: GloContext,
spec: VertexLayoutSpec,
program: ShaderProgram
): VertexLayout => {
const offsetByBufferIndex = new Map<number, number>();
const attributes = spec.attributes
.map(attribute => {
const { bufferIndex, format, name } = attribute;
if (!offsetByBufferIndex.has(bufferIndex)) {
offsetByBufferIndex.set(bufferIndex, 0);
}
const offset = offsetByBufferIndex.get(bufferIndex);
offsetByBufferIndex.set(
bufferIndex,
offset + getVertexFormatSize(format)
);
let location = program.attributeLocations.get(name);
location = location ? location : null;
return {
bufferIndex,
componentCount: getVertexFormatComponentCount(format),
isNormalized: getVertexFormatIsNormalized(format),
location,
offset,
type: getVertexFormatType(context, format),
};
})
.map(attribute => {
return {
...attribute,
stride: offsetByBufferIndex.get(attribute.bufferIndex),
};
});
return {
attributes,
};
};
const defaultRasterizerStateDepthBias = (): RasterizerStateDepthBias => {
return {
clamp: 0,
constant: 0,
slope: 0,
};
};
const defaultStencilOpState = (context: GloContext): StencilOpState => {
const { gl } = context;
return {
compareMask: 0xffffffff,
compareOp: gl.ALWAYS,
depthFailOp: gl.KEEP,
failOp: gl.KEEP,
passOp: gl.KEEP,
reference: 0,
writeMask: 0xffffffff,
};
};
const getBytesPerIndex = (indexType: IndexType): number => {
switch (indexType) {
case "NONE":
return 0;
case "UINT16":
return 2;
case "UINT32":
return 4;
default:
throw new Error(`Index type value ${indexType} is unknown.`);
}
};
const getCompareOp = (context: GloContext, compareOp: CompareOp): GLenum => {
const { gl } = context;
switch (compareOp) {
case "ALWAYS":
return gl.ALWAYS;
case "EQUAL":
return gl.EQUAL;
case "GREATER":
return gl.GREATER;
case "GREATER_OR_EQUAL":
return gl.GEQUAL;
case "LESS":
return gl.LESS;
case "LESS_OR_EQUAL":
return gl.LEQUAL;
case "NEVER":
return gl.NEVER;
case "NOT_EQUAL":
return gl.NOTEQUAL;
default:
throw new Error(`Compare op value ${compareOp} is unknown.`);
}
};
const getCullMode = (context: GloContext, cullMode: CullMode): GLenum => {
const { gl } = context;
switch (cullMode) {
case "BACK":
return gl.BACK;
case "FRONT":
return gl.FRONT;
case "NONE":
return gl.FRONT_AND_BACK;
default:
throw new Error(`Cull mode value ${cullMode} is unknown.`);
}
};
const getFaceWinding = (
context: GloContext,
faceWinding: FaceWinding
): GLenum => {
const { gl } = context;
switch (faceWinding) {
case "CLOCKWISE":
return gl.CW;
case "COUNTERCLOCKWISE":
return gl.CCW;
default:
throw new Error(`Face winding value ${faceWinding} is unknown.`);
}
};
const getIndexType = (
context: GloContext,
indexType: IndexType
): GLenum | null => {
const { gl } = context;
switch (indexType) {
case "NONE":
return null;
case "UINT16":
return gl.UNSIGNED_SHORT;
case "UINT32":
return gl.UNSIGNED_INT;
default:
throw new Error(`Index type of ${indexType} is unknown.`);
}
};
const getPrimitiveTopology = (
context: GloContext,
primitiveTopology: PrimitiveTopology
): GLenum => {
const { gl } = context;
switch (primitiveTopology) {
case "LINE_LIST":
return gl.LINES;
case "TRIANGLE_LIST":
return gl.TRIANGLES;
default:
throw new Error(
`Primitive topology of type ${primitiveTopology} is unknown.`
);
}
};
const getStencilOp = (context: GloContext, stencilOp: StencilOp): GLenum => {
const { gl } = context;
switch (stencilOp) {
case "DECREMENT_AND_CLAMP":
return gl.DECR;
case "DECREMENT_AND_WRAP":
return gl.DECR_WRAP;
case "INCREMENT_AND_CLAMP":
return gl.INCR;
case "INCREMENT_AND_WRAP":
return gl.INCR_WRAP;
case "INVERT":
return gl.INVERT;
case "KEEP":
return gl.KEEP;
case "REPLACE":
return gl.REPLACE;
case "ZERO":
return gl.ZERO;
default:
throw new Error(`Stencil op value ${stencilOp} is unknown.`);
}
};
const getVertexFormatComponentCount = (vertexFormat: VertexFormat): number => {
switch (vertexFormat) {
case "FLOAT1":
return 1;
case "FLOAT2":
return 2;
case "FLOAT3":
return 3;
case "FLOAT4":
return 4;
case "SBYTE4_NORM":
return 4;
case "UBYTE4_NORM":
return 4;
case "USHORT2_NORM":
return 2;
default:
throw new Error(`Vertex format of type ${vertexFormat} is unknown.`);
}
};
const getVertexFormatIsNormalized = (vertexFormat: VertexFormat): boolean => {
switch (vertexFormat) {
case "FLOAT1":
case "FLOAT2":
case "FLOAT3":
case "FLOAT4":
return false;
case "SBYTE4_NORM":
case "UBYTE4_NORM":
case "USHORT2_NORM":
return true;
default:
throw new Error(`Vertex format of type ${vertexFormat} is unknown.`);
}
};
const getVertexFormatType = (
context: GloContext,
vertexFormat: VertexFormat
): GLenum => {
const { gl } = context;
switch (vertexFormat) {
case "FLOAT1":
case "FLOAT2":
case "FLOAT3":
case "FLOAT4":
return gl.FLOAT;
case "SBYTE4_NORM":
return gl.BYTE;
case "UBYTE4_NORM":
return gl.UNSIGNED_BYTE;
case "USHORT2_NORM":
return gl.UNSIGNED_SHORT;
default:
throw new Error(`Vertex format of type ${vertexFormat} is unknown.`);
}
};
const setDepthStencilState = (
context: GloContext,
state: DepthStencilState
) => {
const { gl } = context;
const { shouldCompareDepth, shouldUseStencil, shouldWriteDepth } = state;
const priorState = context.state.pipeline?.depthStencil;
if (!priorState || shouldCompareDepth !== priorState.shouldCompareDepth) {
if (shouldCompareDepth) {
gl.enable(gl.DEPTH_TEST);
} else {
gl.disable(gl.DEPTH_TEST);
}
}
if (!priorState || shouldWriteDepth !== priorState.shouldWriteDepth) {
gl.depthMask(shouldWriteDepth);
}
if (!priorState || shouldUseStencil !== priorState.shouldUseStencil) {
if (shouldUseStencil) {
gl.enable(gl.STENCIL_TEST);
} else {
gl.disable(gl.STENCIL_TEST);
}
}
if (shouldUseStencil) {
setStencilState(
context,
state.frontStencil,
priorState?.frontStencil,
gl.FRONT
);
setStencilState(
context,
state.backStencil,
priorState?.backStencil,
gl.BACK
);
}
};
const setRasterizerState = (context: GloContext, state: RasterizerState) => {
const { gl } = context;
const priorState = context.state.pipeline?.rasterizer;
if (!priorState || state.cullMode !== priorState.cullMode) {
const wasEnabled = priorState && priorState.cullMode !== gl.FRONT_AND_BACK;
const isEnabled = state.cullMode !== gl.FRONT_AND_BACK;
if (wasEnabled !== isEnabled) {
if (isEnabled) {
gl.enable(gl.CULL_FACE);
} else {
gl.disable(gl.CULL_FACE);
}
}
if (isEnabled) {
gl.cullFace(state.cullMode);
}
}
if (!priorState || state.faceWinding !== priorState.faceWinding) {
gl.frontFace(state.faceWinding);
}
if (
!priorState ||
state.shouldUseDepthBias !== priorState.shouldUseDepthBias
) {
if (state.shouldUseDepthBias) {
gl.enable(gl.POLYGON_OFFSET_FILL);
} else {
gl.disable(gl.POLYGON_OFFSET_FILL);
}
}
if (
!priorState ||
state.depthBias.constant !== priorState.depthBias.constant ||
state.depthBias.slope !== priorState.depthBias.slope
) {
gl.polygonOffset(state.depthBias.slope, state.depthBias.constant);
}
};
const setStencilState = (
context: GloContext,
state: StencilOpState,
priorState: StencilOpState | undefined,
face: GLenum
) => {
const { gl } = context;
const {
compareMask,
compareOp,
depthFailOp,
failOp,
passOp,
reference,
writeMask,
} = state;
if (
!priorState ||
compareMask !== priorState.compareMask ||
compareOp !== priorState.compareOp ||
reference !== priorState.reference
) {
gl.stencilFuncSeparate(face, compareOp, reference, compareMask);
}
if (
!priorState ||
depthFailOp !== priorState.depthFailOp ||
failOp !== priorState.failOp ||
passOp !== priorState.passOp
) {
gl.stencilOpSeparate(face, failOp, depthFailOp, passOp);
}
if (!priorState || writeMask !== priorState.writeMask) {
gl.stencilMaskSeparate(face, writeMask);
}
};
<file_sep>export const getBinaryFile = async (uri: string): Promise<ArrayBuffer> => {
const response = await fetch(uri, {
method: "GET",
});
return response.arrayBuffer();
};
<file_sep>import { Vector2 } from "./Geometry/Vector2";
export const clamp = (x: number, min: number, max: number): number => {
return Math.max(Math.min(x, max), min);
};
export const limitUnitLength = (vector: Vector2): Vector2 => {
const length = vector.length;
if (length > 0) {
return Vector2.divide(vector, length);
}
return vector;
};
<file_sep>import { Rotor3 } from "./Rotor3";
export class Quaternion {
elements: number[];
constructor(elements: number[] = [0, 0, 0, 0]) {
this.elements = elements;
}
get w(): number {
return this.elements[0];
}
get x(): number {
return this.elements[1];
}
get y(): number {
return this.elements[2];
}
get z(): number {
return this.elements[3];
}
set w(w: number) {
this.elements[0] = w;
}
set x(x: number) {
this.elements[1] = x;
}
set y(y: number) {
this.elements[2] = y;
}
set z(z: number) {
this.elements[3] = z;
}
toString(): string {
return `(${this.w}, ${this.x}, ${this.y}, ${this.z})`;
}
}
<file_sep>import { Point3 } from "./Point3";
import { Transform } from "./Transform";
import { Vector3 } from "./Vector3";
import { Vector4 } from "./Vector4";
export class Matrix4 {
rows: Vector4[];
constructor(rows: Vector4[]) {
this.rows = rows;
}
getColumn(index: number): Vector4 {
return new Vector4([
this.rows[0].elements[index],
this.rows[1].elements[index],
this.rows[2].elements[index],
this.rows[3].elements[index],
]);
}
getRow(index: number): Vector4 {
return this.rows[index];
}
static dilation(dilation: Vector3): Matrix4 {
return new Matrix4([
new Vector4([dilation.x, 0, 0, 0]),
new Vector4([0, dilation.y, 0, 0]),
new Vector4([0, 0, dilation.z, 0]),
Vector4.unitW(),
]);
}
static fromTransform(transform: Transform): Matrix4 {
const { orientation, position, scale } = transform;
const { a, b } = orientation;
const { xy, xz, yz } = b;
const a2 = a * a;
const xy2 = xy * xy;
const xz2 = xz * xz;
const yz2 = yz * yz;
const aXy = a * xy;
const aXz = a * xz;
const aYz = a * yz;
const xzYz = xz * yz;
const xyYz = xy * yz;
const xyXz = xy * xz;
return new Matrix4([
new Vector4([
(a2 - xy2 - xz2 + yz2) * scale.x,
2 * (aXy - xzYz) * scale.y,
2 * (aXz - xyYz) * scale.z,
position.x,
]),
new Vector4([
-2 * (xzYz + aXy) * scale.x,
(a2 - xy2 + xz2 - yz2) * scale.y,
2 * (aYz - xyXz) * scale.z,
position.y,
]),
new Vector4([
2 * (xyYz - aXz) * scale.x,
-2 * (aYz + xyXz) * scale.y,
(a2 + xy2 - xz2 - yz2) * scale.z,
position.z,
]),
Vector4.unitW(),
]);
}
static identity(): Matrix4 {
return new Matrix4([
Vector4.unitX(),
Vector4.unitY(),
Vector4.unitZ(),
Vector4.unitW(),
]);
}
static inverse(m: Matrix4): Matrix4 {
const r = m.rows;
const s = [
r[0].x * r[1].y - r[1].x * r[0].y,
r[0].x * r[1].z - r[1].x * r[0].z,
r[0].x * r[1].w - r[1].x * r[0].w,
r[0].y * r[1].z - r[1].y * r[0].z,
r[0].y * r[1].w - r[1].y * r[0].w,
r[0].z * r[1].w - r[1].z * r[0].w,
];
const c = [
r[2].x * r[3].y - r[3].x * r[2].y,
r[2].x * r[3].z - r[3].x * r[2].z,
r[2].x * r[3].w - r[3].x * r[2].w,
r[2].y * r[3].z - r[3].y * r[2].z,
r[2].y * r[3].w - r[3].y * r[2].w,
r[2].z * r[3].w - r[3].z * r[2].w,
];
const determinant =
s[0] * c[5] -
s[1] * c[4] +
s[2] * c[3] +
s[3] * c[2] -
s[4] * c[1] +
s[5] * c[0];
if (determinant === 0) {
return m;
}
const d = 1 / determinant;
return new Matrix4([
new Vector4([
d * (r[1].y * c[5] - r[1].z * c[4] + r[1].w * c[3]),
d * (-r[0].y * c[5] + r[0].z * c[4] - r[0].w * c[3]),
d * (r[3].y * s[5] - r[3].z * s[4] + r[3].w * s[3]),
d * (-r[2].y * s[5] + r[2].z * s[4] - r[2].w * s[3]),
]),
new Vector4([
d * (-r[1].x * c[5] + r[1].z * c[2] - r[1].w * c[1]),
d * (r[0].x * c[5] - r[0].z * c[2] + r[0].w * c[1]),
d * (-r[3].x * s[5] + r[3].z * s[2] - r[3].w * s[1]),
d * (r[2].x * s[5] - r[2].z * s[2] + r[2].w * s[1]),
]),
new Vector4([
d * (r[1].x * c[4] - r[1].y * c[2] + r[1].w * c[0]),
d * (-r[0].x * c[4] + r[0].y * c[2] - r[0].w * c[0]),
d * (r[3].x * s[4] - r[3].y * s[2] + r[3].w * s[0]),
d * (-r[2].x * s[4] + r[2].y * s[2] - r[2].w * s[0]),
]),
new Vector4([
d * (-r[1].x * c[3] + r[1].y * c[1] - r[1].z * c[0]),
d * (r[0].x * c[3] - r[0].y * c[1] + r[0].z * c[0]),
d * (-r[3].x * s[3] + r[3].y * s[1] - r[3].z * s[0]),
d * (r[2].x * s[3] - r[2].y * s[1] + r[2].z * s[0]),
]),
]);
}
/**
* Create a transform from world space to view space.
*
* This assumes a right handed coordinate system.
*
* @param position the view position
* @param target the point to look toward
* @param worldUp the world space up axis
* @return a transform from world space to view space
*/
static lookAtRh(position: Point3, target: Point3, worldUp: Vector3): Matrix4 {
const forward = Vector3.normalize(Point3.subtract(position, target));
const right = Vector3.normalize(Vector3.cross(worldUp, forward));
const up = Vector3.normalize(Vector3.cross(forward, right));
return Matrix4.view(right, up, forward, position);
}
static multiply(a: Matrix4, b: Matrix4): Matrix4 {
const result = Matrix4.identity();
for (let i = 0; i < 4; i++) {
const row = a.rows[i];
for (let j = 0; j < 4; j++) {
const column = b.getColumn(j);
result.rows[i].elements[j] = Vector4.dot(row, column);
}
}
return result;
}
/**
* Create a perspective projection from view space to clip space.
*
* This assumes a right handed coordinate system and clip space whose depth
* is in the range [-1, 1].
*
* @param fovy the vertical field of view in radians
* @param width the width of the cross section
* @param height the height of the cross section
* @param nearPlane the distance to the near plane
* @param farPlane the distance to the far plane
* @return a perspective projection matrix
*/
static perspective(
fovy: number,
width: number,
height: number,
nearPlane: number,
farPlane: number
): Matrix4 {
const coty = 1 / Math.tan(fovy / 2);
const aspectRatio = width / height;
const negDepth = nearPlane - farPlane;
return new Matrix4([
new Vector4([coty / aspectRatio, 0, 0, 0]),
new Vector4([0, coty, 0, 0]),
new Vector4([
0,
0,
(nearPlane + farPlane) / negDepth,
(2 * nearPlane * farPlane) / negDepth,
]),
new Vector4([0, 0, -1, 0]),
]);
}
static toFloat32Array(m: Matrix4): Float32Array {
const elements = m.rows.reduce(
(elements, row) => elements.concat(row.elements),
[] as number[]
);
return new Float32Array(elements);
}
static transformPoint3(m: Matrix4, p: Point3): Point3 {
const r = new Vector4([p.x, p.y, p.z, 1]);
const a = Vector4.dot(m.rows[3], r);
return new Point3([
Vector4.dot(m.rows[0], r) / a,
Vector4.dot(m.rows[1], r) / a,
Vector4.dot(m.rows[2], r) / a,
]);
}
static transformVector3(m: Matrix4, v: Vector3): Vector3 {
const r = Vector4.fromVector3(v);
return new Vector3([
Vector4.dot(m.rows[0], r),
Vector4.dot(m.rows[1], r),
Vector4.dot(m.rows[2], r),
]);
}
static translation(translation: Vector3): Matrix4 {
return new Matrix4([
new Vector4([1, 0, 0, translation.x]),
new Vector4([0, 1, 0, translation.y]),
new Vector4([0, 0, 1, translation.z]),
Vector4.unitW(),
]);
}
static transpose(m: Matrix4): Matrix4 {
return new Matrix4([
m.getColumn(0),
m.getColumn(1),
m.getColumn(2),
m.getColumn(3),
]);
}
/**
* Create a transform from world space to view space.
*
* This assumes a right handed coordinate system.
*
* @param position the view position
* @param yaw
* @param pitch
* @param worldUp the world space up axis
* @return a transform from world space to view space
*/
static turnRh(
position: Point3,
yaw: number,
pitch: number,
worldUp: Vector3
): Matrix4 {
const forward = Vector3.normalize(
new Vector3([
Math.cos(pitch) * Math.cos(yaw),
Math.cos(pitch) * Math.sin(yaw),
Math.sin(pitch),
])
);
const right = Vector3.normalize(Vector3.cross(worldUp, forward));
const up = Vector3.normalize(Vector3.cross(forward, right));
return Matrix4.view(right, up, forward, position);
}
/**
* Create a transform from world space to view space.
*
* @param xAxis the orientation X axis of the view
* @param yAxis the orientation Y axis of the view
* @param zAxis the orientation Z axis of the view
* @param position the view position
* @return a view matrix
*/
static view(
xAxis: Vector3,
yAxis: Vector3,
zAxis: Vector3,
position: Point3
): Matrix4 {
const p = Vector3.fromPoint3(position);
return new Matrix4([
new Vector4([xAxis.x, xAxis.y, xAxis.z, -Vector3.dot(xAxis, p)]),
new Vector4([yAxis.x, yAxis.y, yAxis.z, -Vector3.dot(yAxis, p)]),
new Vector4([zAxis.x, zAxis.y, zAxis.z, -Vector3.dot(zAxis, p)]),
Vector4.unitW(),
]);
}
}
<file_sep>import { Point3 } from "./Point3";
import { Vector3 } from "./Vector3";
export class Ray {
direction: Vector3;
origin: Point3;
constructor(origin: Point3, direction: Vector3) {
this.origin = origin;
this.direction = direction;
}
}
<file_sep>import { wedge, biWedge } from "./GeometricAlgebra";
import { Point3 } from "./Point3";
import { Ray } from "./Ray";
import { Triangle } from "./Triangle";
export const intersectRayTriangle = (
ray: Ray,
triangle: Triangle
): number | null => {
const edges = [
Point3.subtract(triangle.vertices[1], triangle.vertices[0]),
Point3.subtract(triangle.vertices[2], triangle.vertices[0]),
];
const p = wedge(ray.direction, edges[1]);
const determinant = biWedge(p, edges[0]).xyz;
if (Math.abs(determinant) < 1e-6) {
return null;
}
const inverseDeterminant = 1 / determinant;
const s = Point3.subtract(ray.origin, triangle.vertices[0]);
const u = inverseDeterminant * biWedge(p, s).xyz;
if (u < 0 || u > 1) {
return null;
}
const q = wedge(s, edges[0]);
const v = inverseDeterminant * biWedge(q, ray.direction).xyz;
if (v < 0 || u + v > 1) {
return null;
}
return biWedge(q, edges[1]).xyz;
};
<file_sep>export class Bivector2 {
xy: number;
constructor(xy: number = 0) {
this.xy = xy;
}
}
<file_sep>import { flatMap } from "./Array";
import { Camera, getProjection, getView } from "./Camera";
import { clamp } from "./Clamp";
import { Color } from "./Color";
import { COLORS } from "./Colors";
import { getBinaryFile } from "./Fetch";
import { Bivector3 } from "./Geometry/Bivector3";
import { Matrix4 } from "./Geometry/Matrix4";
import { Point3 } from "./Geometry/Point3";
import { Rotor3 } from "./Geometry/Rotor3";
import { Vector2 } from "./Geometry/Vector2";
import { Vector3 } from "./Geometry/Vector3";
import {
Action,
Axis2dDirection,
createInputState,
getAxis2d,
InputState,
KeyboardEventKey,
KeyMapping,
KeyMappingType,
updateInput,
} from "./Input";
import { packSnorm } from "./Packing";
import {
addCuboid,
addLineSegment,
addSphere,
createPrimitiveContext,
PrimitiveContext,
resetPrimitives,
} from "./Primitive";
import { drawPrimitives, PRIMITIVE_BATCH_CAP_IN_BYTES } from "./PrimitiveDraw";
import * as Dwn from "./SceneFile";
import testDwn from "./Scenes/test.dwn";
import basicPixelSource from "./Shaders/basic.ps.glsl";
import basicVertexSource from "./Shaders/basic.vs.glsl";
import litPixelSource from "./Shaders/lit.ps.glsl";
import litVertexSource from "./Shaders/lit.vs.glsl";
import visualizeNormalPixelSource from "./Shaders/visualize_normal.ps.glsl";
import visualizeNormalVertexSource from "./Shaders/visualize_normal.vs.glsl";
import { Size2 } from "./Size2";
import {
BufferFormat,
BufferSpec,
BufferUsage,
createBuffer,
GloBuffer,
} from "./WebGL/GloBuffer";
import { clearTarget, draw, GloContext } from "./WebGL/GloContext";
import {
createPipeline,
getVertexFormatSize,
Pipeline,
setPipeline,
VertexFormat,
} from "./WebGL/Pipeline";
import { createShader } from "./WebGL/Shader";
import {
createShaderProgram,
setUniform3fv,
setUniformMatrix4fv,
ShaderProgram,
} from "./WebGL/ShaderProgram";
import { setViewport } from "./WebGL/Viewport";
import { Transform } from "./Geometry/Transform";
export interface App {
buffers: BufferSet;
bufferChangeset: Changeset<BufferSpec>;
camera: Camera;
canvasSize: Size2;
context: GloContext;
handleMouseMove?: HandleMouseMove;
input: InputState;
meshes: MeshObject[];
meshChangeset: Changeset<MeshSpec>;
pipelines: PipelineSet;
primitiveContext: PrimitiveContext;
programs: ShaderProgramSet;
transformNodes: TransformNode[];
transformNodeChangeset: Changeset<TransformNodeSpec>;
}
interface Changeset<T> {
added: T[];
}
interface BufferSet {
dynamic: GloBuffer[];
primitiveIndex: GloBuffer;
primitiveVertex: GloBuffer;
}
interface DirectionalLight {
direction: Vector3;
radiance: Vector3;
}
export type HandleMouseMove = (event: MouseEvent) => void;
interface MeshObject {
indexBuffer: GloBuffer;
indicesCount: number;
startIndex: number;
vertexBuffers: GloBuffer[];
}
interface MeshSpec {
indexBufferIndex: number;
indicesCount: number;
startIndex: number;
vertexBufferIndices: number[];
}
interface PipelineSet {
line: Pipeline;
surface: Pipeline;
visualizeNormal: Pipeline;
}
interface PointLight {
position: Point3;
radiance: Vector3;
}
interface ShaderProgramSet {
basic: ShaderProgram;
lit: ShaderProgram;
visualizeNormal: ShaderProgram;
}
interface TransformNode {
children: TransformNode[];
object: MeshObject;
parent: TransformNode | null;
transform: Transform;
}
interface TransformNodeSpec {
children: TransformNodeSpec[];
objectIndex: number;
parent: TransformNodeSpec | null;
transform: Transform;
}
export const createApp = (
context: GloContext,
initialCanvasSize: Size2
): App => {
const keyMappings = createKeyMappings();
const programs = createShaderProgramSet(context);
const app: App = {
buffers: createBufferSet(context),
bufferChangeset: createChangeset(),
camera: {
farClipPlane: 100,
nearClipPlane: 0.001,
pitch: 0,
position: new Point3([0, 0, 1]),
verticalFieldOfView: Math.PI / 2,
yaw: 0,
},
canvasSize: initialCanvasSize,
context,
input: createInputState(keyMappings),
meshes: [],
meshChangeset: createChangeset(),
pipelines: createPipelineSet(context, programs),
primitiveContext: createPrimitiveContext(),
programs,
transformNodes: [],
transformNodeChangeset: createChangeset(),
};
loadScenes(app);
return app;
};
export const handleResize = (event: UIEvent, app: App): any => {
const height = window.innerHeight;
const width = window.innerWidth;
console.log(`resize event: ${width}x${height}`);
};
export const updateFrame = (app: App) => {
const {
camera,
context,
input,
pipelines,
primitiveContext,
programs,
transformNodes,
} = app;
updateInput(input);
updateCamera(camera, input);
const addedBufferStartIndex = updateBufferChangeset(app);
const addedMeshStartIndex = updateMeshChangeset(app, addedBufferStartIndex);
updateTransformNodeChangeset(app, addedMeshStartIndex);
resetPrimitives(primitiveContext);
addLineSegment(primitiveContext, {
endpoints: [new Point3([1, 0, -1]), new Point3([0, 1, 1])],
style: { color: COLORS.white },
});
addAxisIndicator(primitiveContext);
addSphere(primitiveContext, {
center: new Point3([2, 2, 1]),
radius: 1,
style: { color: COLORS.white },
});
addSphere(primitiveContext, {
center: new Point3([-2, 2, 0]),
radius: 0.5,
style: { color: COLORS.white },
});
addCuboid(primitiveContext, {
center: new Point3([0, -3, 0.5]),
orientation: Rotor3.fromAngleAndPlane(Math.PI / 3, Bivector3.unitXZ()),
size: { width: 1, height: 0.5, depth: 2 },
style: { color: COLORS.white },
});
addCuboid(primitiveContext, {
center: new Point3([2, -2, 1]),
size: { width: 1, height: 1, depth: 1 },
style: { color: COLORS.white },
});
addCuboid(primitiveContext, {
center: new Point3([0, 0, -0.5]),
size: { width: 10, height: 0.1, depth: 10 },
style: { color: COLORS.white },
});
clearTarget(context, {
color: {
shouldClear: true,
value: Color.opaqueBlack(),
},
});
setViewport(context, {
bottomLeftX: 0,
bottomLeftY: 0,
farPlane: 1,
height: app.canvasSize.height,
nearPlane: 0,
width: app.canvasSize.width,
});
const model = Matrix4.identity();
const view = getView(camera);
const projection = getProjection(
camera,
app.canvasSize.width,
app.canvasSize.height
);
const modelView = Matrix4.multiply(view, model);
const modelViewProjection = Matrix4.multiply(projection, modelView);
const lightDirection = new Vector3([-0.5345, -0.8018, -0.2673]);
const directionalLight: DirectionalLight = {
direction: lightDirection,
radiance: new Vector3([1, 1, 1]),
};
const pointLight: PointLight = {
position: new Point3([1, -1, 1]),
radiance: new Vector3([1, 1, 1]),
};
setPipeline(context, pipelines.surface);
setUniform3fv(
context,
programs.lit,
"directional_light.direction",
Vector3.toFloat32Array(directionalLight.direction)
);
setUniform3fv(
context,
programs.lit,
"directional_light.radiance",
Vector3.toFloat32Array(directionalLight.radiance)
);
setUniform3fv(
context,
programs.lit,
"point_light.position",
Point3.toFloat32Array(pointLight.position)
);
setUniform3fv(
context,
programs.lit,
"point_light.radiance",
Vector3.toFloat32Array(pointLight.radiance)
);
setUniformMatrix4fv(
context,
programs.lit,
"model",
Matrix4.toFloat32Array(Matrix4.transpose(model))
);
setUniformMatrix4fv(
context,
programs.lit,
"model_view_projection",
Matrix4.toFloat32Array(Matrix4.transpose(modelViewProjection))
);
setUniform3fv(
context,
programs.lit,
"view_position",
Point3.toFloat32Array(camera.position)
);
drawPrimitives(app);
transformNodes
.map((transformNode) => Matrix4.fromTransform(transformNode.transform))
.forEach((model, index) => {
const transformNode = transformNodes[index];
const mesh = transformNode.object;
const modelView = Matrix4.multiply(view, model);
const modelViewProjection = Matrix4.multiply(projection, modelView);
setUniformMatrix4fv(
context,
programs.lit,
"model",
Matrix4.toFloat32Array(Matrix4.transpose(model))
);
setUniformMatrix4fv(
context,
programs.lit,
"model_view_projection",
Matrix4.toFloat32Array(Matrix4.transpose(modelViewProjection))
);
draw(context, mesh);
});
};
const addAxisIndicator = (context: PrimitiveContext) => {
const origin = Point3.zero();
const xAxis = Point3.fromVector3(Vector3.unitX());
const yAxis = Point3.fromVector3(Vector3.unitY());
const zAxis = Point3.fromVector3(Vector3.unitZ());
addLineSegment(context, {
endpoints: [origin, xAxis],
style: { color: COLORS.orange },
});
addLineSegment(context, {
endpoints: [origin, yAxis],
style: { color: COLORS.lightGreen },
});
addLineSegment(context, {
endpoints: [origin, zAxis],
style: { color: COLORS.blue },
});
};
const createBufferSet = (context: GloContext): BufferSet => {
const primitiveIndex = createBuffer(context, {
byteCount: PRIMITIVE_BATCH_CAP_IN_BYTES,
format: BufferFormat.IndexBuffer,
usage: BufferUsage.Dynamic,
});
const primitiveVertex = createBuffer(context, {
byteCount: PRIMITIVE_BATCH_CAP_IN_BYTES,
format: BufferFormat.VertexBuffer,
usage: BufferUsage.Dynamic,
});
return {
dynamic: [],
primitiveVertex,
primitiveIndex,
};
};
function createChangeset<T>(): Changeset<T> {
return {
added: [],
};
}
const createKeyMappings = (): KeyMapping[] => {
return [
{
action: Action.Move,
direction: Axis2dDirection.PositiveY,
key: KeyboardEventKey.W,
type: KeyMappingType.Axis2d,
},
{
action: Action.Move,
direction: Axis2dDirection.NegativeY,
key: KeyboardEventKey.S,
type: KeyMappingType.Axis2d,
},
{
action: Action.Move,
direction: Axis2dDirection.PositiveX,
key: KeyboardEventKey.D,
type: KeyMappingType.Axis2d,
},
{
action: Action.Move,
direction: Axis2dDirection.NegativeX,
key: KeyboardEventKey.A,
type: KeyMappingType.Axis2d,
},
];
};
const createMesh = (
app: App,
spec: MeshSpec,
addedBufferStartIndex: number
): MeshObject => {
const { buffers } = app;
const {
indexBufferIndex,
indicesCount,
startIndex,
vertexBufferIndices,
} = spec;
const mesh: MeshObject = {
indexBuffer: buffers.dynamic[indexBufferIndex + addedBufferStartIndex],
indicesCount,
startIndex,
vertexBuffers: vertexBufferIndices.map(
(index) => buffers.dynamic[index + addedBufferStartIndex]
),
};
return mesh;
};
const createPipelineSet = (
context: GloContext,
programs: ShaderProgramSet
): PipelineSet => {
const line = createPipeline(context, {
depthStencil: {
shouldCompareDepth: true,
shouldWriteDepth: true,
shouldUseStencil: false,
},
inputAssembly: {
indexType: "UINT16",
primitiveTopology: "LINE_LIST",
},
shader: programs.basic,
vertexLayout: {
attributes: [
{ bufferIndex: 0, format: "FLOAT3", name: "vertex_position" },
{ bufferIndex: 0, format: "UBYTE4_NORM", name: "vertex_color" },
],
},
});
const surface = createPipeline(context, {
depthStencil: {
shouldCompareDepth: true,
shouldWriteDepth: true,
shouldUseStencil: false,
},
inputAssembly: {
indexType: "UINT16",
primitiveTopology: "TRIANGLE_LIST",
},
shader: programs.lit,
vertexLayout: {
attributes: [
{ bufferIndex: 0, format: "FLOAT3", name: "vertex_position" },
{ bufferIndex: 0, format: "SBYTE4_NORM", name: "vertex_normal" },
{ bufferIndex: 0, format: "UBYTE4_NORM", name: "vertex_color" },
],
},
});
const visualizeNormal = createPipeline(context, {
depthStencil: {
shouldCompareDepth: true,
shouldWriteDepth: true,
shouldUseStencil: false,
},
inputAssembly: {
indexType: "UINT16",
primitiveTopology: "TRIANGLE_LIST",
},
shader: programs.visualizeNormal,
vertexLayout: {
attributes: [
{ bufferIndex: 0, format: "FLOAT3", name: "vertex_position" },
{ bufferIndex: 0, format: "SBYTE4_NORM", name: "vertex_normal" },
{ bufferIndex: 0, format: "UBYTE4_NORM", name: "vertex_color" },
],
},
});
return {
line,
surface,
visualizeNormal,
};
};
const createShaderProgramSet = (context: GloContext): ShaderProgramSet => {
const basicVertexShader = createShader(context, {
source: basicVertexSource,
type: "VERTEX",
});
const basicPixelShader = createShader(context, {
source: basicPixelSource,
type: "PIXEL",
});
const litVertexShader = createShader(context, {
source: litVertexSource,
type: "VERTEX",
});
const litPixelShader = createShader(context, {
source: litPixelSource,
type: "PIXEL",
});
const visualizeNormalVertexShader = createShader(context, {
source: visualizeNormalVertexSource,
type: "VERTEX",
});
const visualizeNormalPixelShader = createShader(context, {
source: visualizeNormalPixelSource,
type: "PIXEL",
});
const basic = createShaderProgram(context, {
shaders: {
pixel: basicPixelShader,
vertex: basicVertexShader,
},
uniforms: ["model_view_projection"],
vertexLayout: {
attributes: [{ name: "vertex_position" }, { name: "vertex_color" }],
},
});
const lit = createShaderProgram(context, {
shaders: {
pixel: litPixelShader,
vertex: litVertexShader,
},
uniforms: [
"directional_light.direction",
"directional_light.radiance",
"model",
"model_view_projection",
"point_light.position",
"point_light.radiance",
"view_position",
],
vertexLayout: {
attributes: [
{ name: "vertex_position" },
{ name: "vertex_normal" },
{ name: "vertex_color" },
],
},
});
const visualizeNormal = createShaderProgram(context, {
shaders: {
pixel: visualizeNormalPixelShader,
vertex: visualizeNormalVertexShader,
},
uniforms: ["model", "model_view_projection"],
vertexLayout: {
attributes: [{ name: "vertex_position" }, { name: "vertex_normal" }],
},
});
return {
basic,
lit,
visualizeNormal,
};
};
const createTransformNode = (
app: App,
spec: TransformNodeSpec,
addedMeshStartIndex: number
): TransformNode => {
const { meshes } = app;
const { objectIndex, transform } = spec;
const transformNode: TransformNode = {
children: [],
object: meshes[objectIndex + addedMeshStartIndex],
parent: null,
transform,
};
return transformNode;
};
const getAccessorByType = (
vertexAttributes: Dwn.VertexAttribute[],
type: Dwn.VertexAttributeType
): Dwn.Accessor => {
const attribute = vertexAttributes.find(
(vertexAttribute) => vertexAttribute.type === type
);
return attribute.accessor;
};
const interleaveAttributes = (
attributes: Dwn.VertexAttribute[]
): ArrayBuffer => {
const types = [
Dwn.VertexAttributeType.Position,
Dwn.VertexAttributeType.Normal,
Dwn.VertexAttributeType.Color,
];
const targetVertexFormats: VertexFormat[] = [
"FLOAT3",
"SBYTE4_NORM",
"UBYTE4_NORM",
];
const accessors = types.map((type) => getAccessorByType(attributes, type));
const targetByteStride = targetVertexFormats.reduce(
(byteStride, vertexFormat) => {
const bytesPerAttribute = getVertexFormatSize(vertexFormat);
return byteStride + bytesPerAttribute;
},
0
);
const vertexCount = Dwn.getElementCount(accessors[0]);
const vertices = new ArrayBuffer(targetByteStride * vertexCount);
for (let i = 0; i < vertexCount; i++) {
const vertexByteIndex = targetByteStride * i;
let attributeByteOffset = 0;
for (let j = 0; j < accessors.length; j++) {
const accessor = accessors[j];
const targetVertexFormat = targetVertexFormats[j];
const { buffer, byteIndex, componentCount, componentType } = accessor;
const startByteIndex = accessor.byteStride * i + byteIndex;
const attributeByteIndex = vertexByteIndex + attributeByteOffset;
switch (componentType) {
case Dwn.ComponentType.Float32: {
const sourceView = new DataView(buffer);
const bytesPerFloat32 = 4;
switch (targetVertexFormat) {
case "FLOAT3": {
const targetView = new Float32Array(vertices, attributeByteIndex);
for (let k = 0; k < componentCount; k++) {
targetView[k] = sourceView.getFloat32(
bytesPerFloat32 * k + startByteIndex,
true
);
}
break;
}
case "SBYTE4_NORM": {
const targetView = new Int8Array(vertices, attributeByteIndex);
for (let k = 0; k < componentCount; k++) {
const value = sourceView.getFloat32(
bytesPerFloat32 * k + startByteIndex,
true
);
targetView[k] = packSnorm(value);
}
break;
}
}
break;
}
case Dwn.ComponentType.Uint8: {
const sourceView = new DataView(buffer);
const targetView = new Uint8Array(vertices, attributeByteIndex);
switch (targetVertexFormat) {
case "UBYTE4_NORM": {
for (let k = 0; k < componentCount; k++) {
targetView[k] = sourceView.getUint8(k + startByteIndex);
}
break;
}
}
break;
}
}
attributeByteOffset += getVertexFormatSize(targetVertexFormat);
}
}
return vertices;
};
const loadScenes = async (app: App) => {
const { bufferChangeset, meshChangeset, transformNodeChangeset } = app;
const fileContent = await getBinaryFile(testDwn);
const scene = Dwn.deserialize(fileContent);
const addedBuffers = flatMap(scene.meshes, (mesh) => {
const indexBufferContent = mesh.indexAccessor.buffer;
const indexBuffer: BufferSpec = {
byteCount: indexBufferContent.byteLength,
content: indexBufferContent,
format: BufferFormat.IndexBuffer,
usage: BufferUsage.Static,
};
const vertexBufferContent = interleaveAttributes(
mesh.vertexLayout.vertexAttributes
);
const vertexBuffer: BufferSpec = {
byteCount: vertexBufferContent.byteLength,
content: vertexBufferContent,
format: BufferFormat.VertexBuffer,
usage: BufferUsage.Static,
};
return [indexBuffer, vertexBuffer];
});
const addedMeshIndexByMesh = new Map<Dwn.Mesh, number>();
const addedMeshes = scene.meshes.map((mesh, meshIndex) => {
const meshSpec: MeshSpec = {
indexBufferIndex: 2 * meshIndex,
indicesCount: Dwn.getElementCount(mesh.indexAccessor),
startIndex: 0,
vertexBufferIndices: [2 * meshIndex + 1],
};
addedMeshIndexByMesh.set(mesh, meshIndex);
return meshSpec;
});
const addedTransformNodeByTransformNode = new Map<
Dwn.TransformNode,
TransformNodeSpec
>();
const addedTransformNodes = scene.transformNodes.map((transformNode) => {
const { object, transform } = transformNode;
const spec: TransformNodeSpec = {
children: [],
objectIndex: addedMeshIndexByMesh.get(object.mesh),
parent: null,
transform,
};
addedTransformNodeByTransformNode.set(transformNode, spec);
return spec;
});
addedTransformNodes.forEach((transformNode, index) => {
const spec = scene.transformNodes[index];
const { children, parent } = spec;
transformNode.children = children.map(
addedTransformNodeByTransformNode.get,
addedTransformNodeByTransformNode
);
transformNode.parent = parent
? addedTransformNodeByTransformNode.get(parent)
: null;
});
bufferChangeset.added = addedBuffers;
meshChangeset.added = addedMeshes;
transformNodeChangeset.added = addedTransformNodes;
};
const updateBufferChangeset = (app: App): number => {
const { buffers, bufferChangeset, context } = app;
const addedBuffers = bufferChangeset.added;
bufferChangeset.added = [];
const newBuffers = addedBuffers.map((spec) => createBuffer(context, spec));
const addedBufferStartIndex = buffers.dynamic.length;
buffers.dynamic = buffers.dynamic.concat(newBuffers);
return addedBufferStartIndex;
};
const updateMeshChangeset = (
app: App,
addedBufferStartIndex: number
): number => {
const { meshes, meshChangeset } = app;
const addedMeshes = meshChangeset.added;
meshChangeset.added = [];
const newMeshes = addedMeshes.map((spec) =>
createMesh(app, spec, addedBufferStartIndex)
);
const addedMeshStartIndex = meshes.length;
app.meshes = meshes.concat(newMeshes);
return addedMeshStartIndex;
};
const updateTransformNodeChangeset = (
app: App,
addedMeshStartIndex: number
) => {
const { transformNodes, transformNodeChangeset } = app;
const addedTransformNodes = transformNodeChangeset.added;
transformNodeChangeset.added = [];
const addedNodesBySpec = new Map<TransformNodeSpec, TransformNode>();
const newTransformNodes = addedTransformNodes.map((spec) => {
const transformNode = createTransformNode(app, spec, addedMeshStartIndex);
addedNodesBySpec.set(spec, transformNode);
return transformNode;
});
newTransformNodes.forEach((transformNode, index) => {
const spec = addedTransformNodes[index];
const { children, parent } = spec;
transformNode.children = children.map(
addedNodesBySpec.get,
addedNodesBySpec
);
transformNode.parent = parent ? addedNodesBySpec.get(parent) : null;
});
app.transformNodes = transformNodes.concat(newTransformNodes);
};
const updateCamera = (camera: Camera, input: InputState) => {
const { delta } = input.pointer;
const horizontalPixelsPerRadian = 0.001;
const moveSpeed = 0.1;
const verticalPixelsPerRadian = 0.001;
const deltaPitch = verticalPixelsPerRadian * delta.y;
camera.pitch = clamp(camera.pitch - deltaPitch, -Math.PI / 2, Math.PI / 2);
camera.yaw -= horizontalPixelsPerRadian * delta.x;
const direction = Vector2.rotate(
getAxis2d(input, Action.Move),
camera.yaw + Math.PI / 2
);
const velocity = Vector2.multiply(moveSpeed, direction);
camera.position = Point3.add(camera.position, Vector3.fromVector2(velocity));
};
<file_sep>import { GloContext } from "./GloContext";
export type ShaderType = "PIXEL" | "VERTEX";
export interface Shader {
handle: WebGLShader;
}
export interface ShaderSpec {
source: string;
type: ShaderType;
}
export const createShader = (context: GloContext, spec: ShaderSpec): Shader => {
const { gl } = context;
const { source, type } = spec;
const shaderType = getShaderType(context, type);
const shader = gl.createShader(shaderType);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
const infoLog = gl.getShaderInfoLog(shader);
throw new Error("Failed to compile shader: " + infoLog);
}
return {
handle: shader,
};
};
const getShaderType = (context: GloContext, shaderType: ShaderType): GLenum => {
const { gl } = context;
switch (shaderType) {
case "PIXEL":
return gl.FRAGMENT_SHADER;
case "VERTEX":
return gl.VERTEX_SHADER;
default:
throw new Error(`Shader type ${shaderType} is unknown.`);
}
};
<file_sep>import { Vector2 } from "./Vector2";
export class Point2 {
elements: number[];
constructor(elements: number[] = [0, 0]) {
this.elements = elements;
}
get x(): number {
return this.elements[0];
}
get y(): number {
return this.elements[1];
}
set x(x: number) {
this.elements[0] = x;
}
set y(y: number) {
this.elements[1] = y;
}
toString(): string {
return `(${this.x}, ${this.y})`;
}
static add(p: Point2, v: Vector2): Point2 {
return new Point2([p.x + v.x, p.y + v.y]);
}
static subtract(a: Point2, b: Point2): Vector2 {
return new Vector2([a.x - b.x, a.y - b.y]);
}
}
<file_sep>export class Bivector3 {
elements: number[];
constructor(elements: number[] = [0, 0, 0]) {
this.elements = elements;
}
get length(): number {
return Math.sqrt(this.squaredLength);
}
get squaredLength(): number {
const xy = this.xy;
const xz = this.xz;
const yz = this.yz;
return xy * xy + xz * xz + yz * yz;
}
get xy(): number {
return this.elements[0];
}
get xz(): number {
return this.elements[1];
}
get yz(): number {
return this.elements[2];
}
set xy(xy: number) {
this.elements[0] = xy;
}
set xz(xz: number) {
this.elements[1] = xz;
}
set yz(yz: number) {
this.elements[2] = yz;
}
static add(a: Bivector3, b: Bivector3): Bivector3 {
return new Bivector3([a.xy + b.xy, a.xz + b.xz, a.yz + b.yz]);
}
static divide(v: Bivector3, s: number): Bivector3 {
return new Bivector3([v.xy / s, v.xz / s, v.yz / s]);
}
static multiply(s: number, v: Bivector3): Bivector3 {
return new Bivector3([s * v.xy, s * v.xz, s * v.yz]);
}
static negate(v: Bivector3): Bivector3 {
return new Bivector3([-v.xy, -v.xz, -v.yz]);
}
static normalize(v: Bivector3): Bivector3 {
return Bivector3.divide(v, v.length);
}
static pointwiseDivide(a: Bivector3, b: Bivector3): Bivector3 {
return new Bivector3([a.xy / b.xy, a.xz / b.xz, a.yz / b.yz]);
}
static pointwiseMultiply(a: Bivector3, b: Bivector3): Bivector3 {
return new Bivector3([a.xy * b.xy, a.xz * b.xz, a.yz * b.yz]);
}
static subtract(a: Bivector3, b: Bivector3): Bivector3 {
return new Bivector3([a.xy - b.xy, a.xz - b.xz, a.yz - b.yz]);
}
static unitXY(): Bivector3 {
return new Bivector3([1, 0, 0]);
}
static unitXZ(): Bivector3 {
return new Bivector3([0, 1, 0]);
}
static unitYZ(): Bivector3 {
return new Bivector3([0, 0, 1]);
}
}
<file_sep>import { GloContext } from "./GloContext";
import { Shader } from "./Shader";
export interface ShaderProgram {
attributeLocations: Map<string, GLint>;
handle: WebGLProgram;
uniformLocations: Map<string, WebGLUniformLocation>;
}
export interface ShaderProgramSpec {
shaders: {
pixel: Shader;
vertex: Shader;
};
uniforms: string[];
vertexLayout: ShaderVertexLayoutSpec;
}
export interface ShaderVertexAttributeSpec {
name: string;
}
export interface ShaderVertexLayoutSpec {
attributes: ShaderVertexAttributeSpec[];
}
export const createShaderProgram = (
context: GloContext,
spec: ShaderProgramSpec
): ShaderProgram => {
const pixelShader = spec.shaders.pixel;
const vertexShader = spec.shaders.vertex;
const handle = createAndLinkProgram(
context,
vertexShader.handle,
pixelShader.handle
);
const attributeLocations = getAttributeLocations(
context,
handle,
spec.vertexLayout
);
const uniformLocations = getUniformLocations(context, handle, spec.uniforms);
return {
attributeLocations,
handle,
uniformLocations,
};
};
export const setUniform1f = (
context: GloContext,
program: ShaderProgram,
name: string,
value: number
): void => {
const { gl } = context;
const { uniformLocations } = program;
gl.uniform1f(uniformLocations.get(name), value);
};
export const setUniform1i = (
context: GloContext,
program: ShaderProgram,
name: string,
value: number
): void => {
const { gl } = context;
const { uniformLocations } = program;
gl.uniform1i(uniformLocations.get(name), value);
};
export const setUniform3fv = (
context: GloContext,
program: ShaderProgram,
name: string,
value: Float32List
) => {
const { gl } = context;
const { uniformLocations } = program;
gl.uniform3fv(uniformLocations.get(name), value);
};
export const setUniform4fv = (
context: GloContext,
program: ShaderProgram,
name: string,
value: Float32List
) => {
const { gl } = context;
const { uniformLocations } = program;
gl.uniform4fv(uniformLocations.get(name), value);
};
export const setUniformMatrix3fv = (
context: GloContext,
program: ShaderProgram,
name: string,
value: Float32List
) => {
const { gl } = context;
const { uniformLocations } = program;
gl.uniformMatrix3fv(uniformLocations.get(name), false, value);
};
export const setUniformMatrix4fv = (
context: GloContext,
program: ShaderProgram,
name: string,
value: Float32List
) => {
const { gl } = context;
const { uniformLocations } = program;
gl.uniformMatrix4fv(uniformLocations.get(name), false, value);
};
const createAndLinkProgram = (
context: GloContext,
vertexShader: WebGLShader,
fragmentShader: WebGLShader
): WebGLProgram => {
const { gl } = context;
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const infoLog = gl.getProgramInfoLog(program);
throw new Error("Failed to link program: " + infoLog);
}
return program;
};
const getAttributeLocations = (
context: GloContext,
handle: WebGLProgram,
vertexLayout: ShaderVertexLayoutSpec
): Map<string, GLint> => {
const { gl } = context;
const attributeLocationsByName = new Map<string, GLint>();
for (const attribute of vertexLayout.attributes) {
const { name } = attribute;
const location = gl.getAttribLocation(handle, name);
if (location === -1) {
throw new Error(`The location of attribute ${name} was not found.`);
}
attributeLocationsByName.set(name, location);
}
return attributeLocationsByName;
};
const getUniformLocations = (
context: GloContext,
handle: WebGLProgram,
uniformNames: string[]
): Map<string, WebGLUniformLocation> => {
const { gl } = context;
const uniformLocations = new Map<string, WebGLUniformLocation>();
for (const uniformName of uniformNames) {
const location = gl.getUniformLocation(handle, uniformName);
if (!location) {
throw new Error(`The location of uniform ${uniformName} was not found.`);
}
uniformLocations.set(uniformName, location);
}
return uniformLocations;
};
<file_sep>import { GloContext } from "./GloContext";
export enum BufferFormat {
IndexBuffer,
VertexBuffer,
}
export type BufferSpec = BufferSpecContent | BufferSpecEmpty;
interface BufferSpecBase {
format: BufferFormat;
usage: BufferUsage;
}
interface BufferSpecContent extends BufferSpecBase {
content: ArrayBufferView | ArrayBuffer;
}
interface BufferSpecEmpty extends BufferSpecBase {
byteCount: number;
}
export interface BufferUpdate {
buffer: GloBuffer;
content: ArrayBufferView | ArrayBuffer;
offsetInBytes: number;
}
export enum BufferUsage {
Dynamic,
Static,
}
export interface GloBuffer {
format: GLenum;
handle: WebGLBuffer;
}
export const createBuffer = (
context: GloContext,
spec: BufferSpec
): GloBuffer => {
const { gl } = context;
const usage = getBufferUsage(context, spec.usage);
const format = getBufferFormat(context, spec.format);
const buffer = gl.createBuffer();
gl.bindBuffer(format, buffer);
if ("content" in spec) {
gl.bufferData(format, spec.content, usage);
} else {
gl.bufferData(format, spec.byteCount, usage);
}
return {
format,
handle: buffer,
};
};
export const updateBuffer = (context: GloContext, update: BufferUpdate) => {
const { gl } = context;
const { buffer, offsetInBytes, content } = update;
const { format, handle } = buffer;
gl.bindBuffer(format, handle);
gl.bufferSubData(format, offsetInBytes, content);
};
const getBufferFormat = (
context: GloContext,
bufferFormat: BufferFormat
): GLenum => {
const { gl } = context;
switch (bufferFormat) {
case BufferFormat.IndexBuffer:
return gl.ELEMENT_ARRAY_BUFFER;
case BufferFormat.VertexBuffer:
return gl.ARRAY_BUFFER;
default:
throw new Error(`Buffer format value of ${bufferFormat} is unknown.`);
}
};
const getBufferUsage = (
context: GloContext,
bufferUsage: BufferUsage
): GLenum => {
const { gl } = context;
switch (bufferUsage) {
case BufferUsage.Dynamic:
return gl.DYNAMIC_DRAW;
case BufferUsage.Static:
return gl.STATIC_DRAW;
default:
throw new Error(`Buffer usage value of ${bufferUsage} is unknown.`);
}
};
<file_sep>import { App } from "./App";
import { Color } from "./Color";
import { GloBuffer, updateBuffer } from "./WebGL/GloBuffer";
import { GloContext, draw } from "./WebGL/GloContext";
import { setPipeline, getBytesPerVertex } from "./WebGL/Pipeline";
import { Point3 } from "./Geometry/Point3";
import {
LineSegment,
Sphere,
getIndexCount,
getVertexCount,
Cuboid,
} from "./Primitive";
import { Vector3 } from "./Geometry/Vector3";
import { packSByte4FromVector4 } from "./Packing";
import { Vector4 } from "./Geometry/Vector4";
import { rotate } from "./Geometry/GeometricAlgebra";
import { setUniformMatrix4fv } from "./WebGL/ShaderProgram";
import { Matrix4 } from "./Geometry/Matrix4";
import { getView, getProjection } from "./Camera";
export const PRIMITIVE_BATCH_CAP_IN_BYTES = 16384;
interface Batch {
index: {
buffer: GloBuffer;
byteCount: number;
count: number;
};
vertex: {
buffer: GloBuffer;
byteCount: number;
count: number;
};
}
export const drawPrimitives = (app: App) => {
drawLines(app);
drawSurfaces(app);
};
const batchCuboidIndices = (indexBuffer: ArrayBuffer, baseIndex: number) => {
const uint16View = new Uint16Array(indexBuffer);
const verticesPerFace = 4;
const faceCount = 6;
const setByFace = [0, 1, 1, 0, 0, 1];
const cornerIndicesBySet = [
[0, 2, 1, 1, 2, 3],
[0, 1, 2, 1, 3, 2],
];
for (let i = 0; i < faceCount; i++) {
const cornerIndices = cornerIndicesBySet[setByFace[i]];
for (let j = 0; j < cornerIndices.length; j++) {
uint16View[cornerIndices.length * i + j] =
verticesPerFace * i + cornerIndices[j] + baseIndex;
}
}
};
const batchCuboidVertices = (vertexBuffer: ArrayBuffer, cuboid: Cuboid) => {
const { center, orientation, size, style } = cuboid;
const extents = Vector3.divide(Vector3.fromSize3(size), 2);
const componentCount = 5;
const floatView = new Float32Array(vertexBuffer);
const uint32View = new Uint32Array(vertexBuffer);
const color = Color.toRgbaInteger(style.color);
const cornerSigns = [
new Vector3([-1, -1, -1]),
new Vector3([-1, -1, 1]),
new Vector3([-1, 1, -1]),
new Vector3([-1, 1, 1]),
new Vector3([1, -1, -1]),
new Vector3([1, -1, 1]),
new Vector3([1, 1, -1]),
new Vector3([1, 1, 1]),
];
const corners = cornerSigns.map(sign =>
Vector3.pointwiseMultiply(sign, extents)
);
const cornerIndicesByFace = [
[4, 5, 6, 7],
[0, 1, 2, 3],
[2, 3, 6, 7],
[0, 1, 4, 5],
[1, 3, 5, 7],
[0, 2, 4, 6],
];
const faceNormals = [
new Vector3([1, 0, 0]),
new Vector3([-1, 0, 0]),
new Vector3([0, 1, 0]),
new Vector3([0, -1, 0]),
new Vector3([0, 0, 1]),
new Vector3([0, 0, -1]),
];
for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
const cornerIndices = cornerIndicesByFace[faceIndex];
const faceNormal = faceNormals[faceIndex];
const normal = Vector3.normalize(rotate(orientation, faceNormal));
for (let cornerIndex = 0; cornerIndex < 4; cornerIndex++) {
const corner = corners[cornerIndices[cornerIndex]];
const position = Point3.add(center, rotate(orientation, corner));
const vertexIndex = componentCount * (4 * faceIndex + cornerIndex);
batchLitVertex(
floatView,
uint32View,
vertexIndex,
position,
normal,
color
);
}
}
};
const batchLineSegment = (
vertexBuffer: ArrayBuffer,
indexBuffer: ArrayBuffer,
lineSegment: LineSegment,
baseIndex: number
) => {
const { endpoints, style } = lineSegment;
const componentCount = 4;
const color = Color.toRgbaInteger(style.color);
const floatView = new Float32Array(vertexBuffer);
const uint32View = new Uint32Array(vertexBuffer);
for (let i = 0; i < endpoints.length; i++) {
const endpoint = endpoints[i];
batchVertex(floatView, uint32View, componentCount * i, endpoint, color);
}
const uint16View = new Uint16Array(indexBuffer);
for (let i = 0; i < endpoints.length; i++) {
uint16View[i] = baseIndex + i;
}
};
const batchSphereIndices = (indexBuffer: ArrayBuffer, baseIndex: number) => {
const uint16View = new Uint16Array(indexBuffer);
const northPoleIndex = baseIndex;
const southPoleIndex = baseIndex + 1;
const indexAfterPoles = baseIndex + 2;
const meridianCount = 10;
const parallelCount = 6;
const bandCount = parallelCount - 1;
let writeTotal = 0;
const northCapParallel = indexAfterPoles;
for (let i = 0; i < meridianCount; i++) {
const writeIndex = 3 * i;
uint16View[writeIndex] = northPoleIndex;
uint16View[writeIndex + 1] = i + northCapParallel;
uint16View[writeIndex + 2] = ((i + 1) % meridianCount) + northCapParallel;
}
writeTotal += 3 * meridianCount;
const southCapParallel = meridianCount * bandCount + indexAfterPoles;
for (let i = 0; i < meridianCount; i++) {
const writeIndex = 3 * i + writeTotal;
uint16View[writeIndex] = southPoleIndex;
uint16View[writeIndex + 1] = ((i + 1) % meridianCount) + southCapParallel;
uint16View[writeIndex + 2] = i + southCapParallel;
}
writeTotal += 3 * meridianCount;
for (let i = 0; i < bandCount; i++) {
const parallel = [
meridianCount * i,
meridianCount * ((i + 1) % parallelCount),
];
for (let j = 0; j < meridianCount; j++) {
const writeIndex = 6 * (meridianCount * i + j) + writeTotal;
const meridian = [j, (j + 1) % meridianCount];
const indices = [
meridian[0] + parallel[0] + indexAfterPoles,
meridian[0] + parallel[1] + indexAfterPoles,
meridian[1] + parallel[1] + indexAfterPoles,
meridian[1] + parallel[0] + indexAfterPoles,
];
uint16View[writeIndex] = indices[0];
uint16View[writeIndex + 1] = indices[1];
uint16View[writeIndex + 2] = indices[2];
uint16View[writeIndex + 3] = indices[0];
uint16View[writeIndex + 4] = indices[2];
uint16View[writeIndex + 5] = indices[3];
}
}
};
const batchSphereVertices = (vertexBuffer: ArrayBuffer, sphere: Sphere) => {
const { center, radius, style } = sphere;
const componentCount = 5;
const floatView = new Float32Array(vertexBuffer);
const uint32View = new Uint32Array(vertexBuffer);
const color = Color.toRgbaInteger(style.color);
const meridianCount = 10;
const parallelCount = 6;
const deltaInclinationPerParallel = Math.PI / (parallelCount + 1);
const deltaAzimuthPerMeridian = (2 * Math.PI) / meridianCount;
const northPole = Point3.add(
center,
Vector3.multiply(radius, Vector3.unitZ())
);
batchLitVertex(floatView, uint32View, 0, northPole, Vector3.unitZ(), color);
const southPole = Point3.add(
center,
Vector3.multiply(-radius, Vector3.unitZ())
);
batchLitVertex(
floatView,
uint32View,
componentCount,
southPole,
Vector3.negate(Vector3.unitZ()),
color
);
const indexAfterPoles = 2 * componentCount;
for (let parallel = 0; parallel < parallelCount; parallel++) {
const inclination = (parallel + 1) * deltaInclinationPerParallel;
for (let meridian = 0; meridian < meridianCount; meridian++) {
const azimuth = meridian * deltaAzimuthPerMeridian;
const direction = Vector3.fromSphericalCoordinates(
radius,
inclination,
azimuth
);
const point = Point3.add(center, direction);
const pointIndex = meridianCount * parallel + meridian;
const vertexIndex = componentCount * pointIndex + indexAfterPoles;
const normal = Vector3.normalize(direction);
batchLitVertex(floatView, uint32View, vertexIndex, point, normal, color);
}
}
};
const batchVertex = (
floatView: Float32Array,
uint32View: Uint32Array,
index: number,
point: Point3,
colorInteger: number
) => {
floatView[index] = point.x;
floatView[index + 1] = point.y;
floatView[index + 2] = point.z;
uint32View[index + 3] = colorInteger;
};
const batchLitVertex = (
floatView: Float32Array,
uint32View: Uint32Array,
index: number,
point: Point3,
normal: Vector3,
colorInteger: number
) => {
floatView[index] = point.x;
floatView[index + 1] = point.y;
floatView[index + 2] = point.z;
uint32View[index + 3] = packSByte4FromVector4(Vector4.fromVector3(normal));
uint32View[index + 4] = colorInteger;
};
const completeBatch = (context: GloContext, batch: Batch) => {
if (batch.index.count === 0) {
return;
}
draw(context, {
indicesCount: batch.index.count,
startIndex: 0,
indexBuffer: batch.index.buffer,
vertexBuffers: [batch.vertex.buffer],
});
};
const createBatch = (
vertexBuffer: GloBuffer,
indexBuffer: GloBuffer
): Batch => {
return {
index: {
buffer: indexBuffer,
byteCount: 0,
count: 0,
},
vertex: {
buffer: vertexBuffer,
byteCount: 0,
count: 0,
},
};
};
const drawBatchIfFull = (
context: GloContext,
batch: Batch,
indexByteCount: number,
vertexByteCount: number
) => {
if (
batch.index.byteCount + indexByteCount < PRIMITIVE_BATCH_CAP_IN_BYTES &&
batch.vertex.byteCount + vertexByteCount < PRIMITIVE_BATCH_CAP_IN_BYTES
) {
return;
}
draw(context, {
indicesCount: batch.index.count,
startIndex: 0,
indexBuffer: batch.index.buffer,
vertexBuffers: [batch.vertex.buffer],
});
batch.index.byteCount = 0;
batch.vertex.byteCount = 0;
batch.index.count = 0;
batch.vertex.count = 0;
};
const drawLines = (app: App) => {
const {
buffers,
camera,
context,
pipelines,
primitiveContext,
programs,
} = app;
const batch = createBatch(buffers.primitiveVertex, buffers.primitiveIndex);
const linePrimitives = primitiveContext.primitives.filter(
primitive => primitive.type === "LINE_SEGMENT"
);
setPipeline(context, pipelines.line);
const bytesPerIndex = pipelines.line.inputAssembly.bytesPerIndex;
const bytesPerVertex = getBytesPerVertex(pipelines.line.vertexLayout, 0);
const model = Matrix4.identity();
const view = getView(camera);
const projection = getProjection(
camera,
app.canvasSize.width,
app.canvasSize.height
);
const modelView = Matrix4.multiply(view, model);
const modelViewProjection = Matrix4.multiply(projection, modelView);
setUniformMatrix4fv(
context,
programs.basic,
"model_view_projection",
Matrix4.toFloat32Array(Matrix4.transpose(modelViewProjection))
);
for (const primitive of linePrimitives) {
const indexCount = getIndexCount(primitive);
const vertexCount = getVertexCount(primitive);
const indexByteCount = bytesPerIndex * indexCount;
const vertexByteCount = bytesPerVertex * vertexCount;
drawBatchIfFull(context, batch, indexByteCount, vertexByteCount);
const indexBuffer = new ArrayBuffer(indexByteCount);
const vertexBuffer = new ArrayBuffer(vertexByteCount);
switch (primitive.type) {
case "LINE_SEGMENT":
batchLineSegment(
vertexBuffer,
indexBuffer,
primitive,
batch.vertex.count
);
break;
}
updateBuffer(context, {
buffer: batch.vertex.buffer,
content: vertexBuffer,
offsetInBytes: batch.vertex.byteCount,
});
updateBuffer(context, {
buffer: batch.index.buffer,
content: indexBuffer,
offsetInBytes: batch.index.byteCount,
});
batch.index.byteCount += indexByteCount;
batch.vertex.byteCount += vertexByteCount;
batch.index.count += indexCount;
batch.vertex.count += vertexCount;
}
completeBatch(context, batch);
};
const drawSurfaces = (app: App) => {
const { buffers, context, pipelines, primitiveContext } = app;
const batch = createBatch(buffers.primitiveVertex, buffers.primitiveIndex);
const surfacePrimitives = primitiveContext.primitives.filter(
primitive => primitive.type === "CUBOID" || primitive.type === "SPHERE"
);
setPipeline(context, pipelines.surface);
const bytesPerIndex = pipelines.surface.inputAssembly.bytesPerIndex;
const bytesPerVertex = getBytesPerVertex(pipelines.surface.vertexLayout, 0);
for (const primitive of surfacePrimitives) {
const indexCount = getIndexCount(primitive);
const vertexCount = getVertexCount(primitive);
const vertexByteCount = bytesPerVertex * vertexCount;
const indexByteCount = bytesPerIndex * indexCount;
drawBatchIfFull(context, batch, indexByteCount, vertexByteCount);
const indexBuffer = new ArrayBuffer(indexByteCount);
const vertexBuffer = new ArrayBuffer(vertexByteCount);
switch (primitive.type) {
case "CUBOID":
batchCuboidVertices(vertexBuffer, primitive);
batchCuboidIndices(indexBuffer, batch.vertex.count);
break;
case "SPHERE":
batchSphereVertices(vertexBuffer, primitive);
batchSphereIndices(indexBuffer, batch.vertex.count);
break;
}
updateBuffer(context, {
buffer: batch.vertex.buffer,
content: vertexBuffer,
offsetInBytes: batch.vertex.byteCount,
});
updateBuffer(context, {
buffer: batch.index.buffer,
content: indexBuffer,
offsetInBytes: batch.index.byteCount,
});
batch.index.byteCount += indexByteCount;
batch.vertex.byteCount += vertexByteCount;
batch.index.count += indexCount;
batch.vertex.count += vertexCount;
}
completeBatch(context, batch);
};
<file_sep>import { Point3 } from "./Point3";
import { Rotor3 } from "./Rotor3";
import { Vector3 } from "./Vector3";
export interface Transform {
orientation: Rotor3;
position: Point3;
scale: Vector3;
}
<file_sep>import { Texture } from "./Texture";
import { GloContext } from "./GloContext";
import { TraceError } from "../TraceError";
export interface Attachment {
mipLevel: number;
point: GLenum;
slice: number;
texture: Texture;
}
export interface AttachmentSpec {
mipLevel: number;
slice: number;
texture: Texture;
}
export interface Pass {
colorAttachments: Attachment[];
depthStencilAttachment: Attachment;
framebuffer: WebGLFramebuffer;
}
export interface PassSpec {
colorAttachments: Attachment[];
depthStencilAttachment: Attachment;
}
export const bindPass = (context: GloContext, pass: Pass | null): void => {
const { gl } = context;
const drawBuffersExt = context.extensions.drawBuffers;
gl.bindFramebuffer(gl.FRAMEBUFFER, pass ? pass.framebuffer : null);
const drawAttachments = pass.colorAttachments.map(
attachment => attachment.point
);
drawBuffersExt.drawBuffersWEBGL(drawAttachments);
};
export const createPass = (context: GloContext, spec: PassSpec): Pass => {
const { gl } = context;
const colorAttachmentSpecs = spec.colorAttachments;
const depthStencilAttachmentSpec = spec.depthStencilAttachment;
const framebuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
const colorAttachments = colorAttachmentSpecs.map((attachmentSpec, index) => {
const point = gl.COLOR_ATTACHMENT0 + index;
return createAttachment(context, attachmentSpec, point);
});
const depthStencilAttachment = createAttachment(
context,
depthStencilAttachmentSpec,
getDepthStencilAttachmentPoint(context, depthStencilAttachmentSpec)
);
const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
if (status !== gl.FRAMEBUFFER_COMPLETE) {
let name;
try {
name = getFramebufferStatusName(context, status);
} catch (error) {
throw new TraceError(error, "Framebuffer status check failed.");
}
throw new Error(`Framebuffer status check failed with status ${name}.`);
}
return {
colorAttachments,
depthStencilAttachment,
framebuffer,
};
};
const createAttachment = (
context: GloContext,
spec: AttachmentSpec,
point: GLenum
): Attachment => {
const { gl } = context;
const { mipLevel, slice, texture } = spec;
switch (texture.type) {
case "2D":
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
point,
gl.TEXTURE_2D,
texture.handle,
mipLevel
);
break;
case "CUBE":
const target = getCubeFaceTarget(context, slice);
gl.framebufferTexture2D(gl.FRAMEBUFFER, point, target, texture, mipLevel);
break;
}
return {
mipLevel,
point,
slice,
texture,
};
};
const getCubeFaceTarget = (context: GloContext, slice: number): GLenum => {
const { gl } = context;
switch (slice) {
default:
case 0:
return gl.TEXTURE_CUBE_MAP_POSITIVE_X;
case 1:
return gl.TEXTURE_CUBE_MAP_NEGATIVE_X;
case 2:
return gl.TEXTURE_CUBE_MAP_POSITIVE_Y;
case 3:
return gl.TEXTURE_CUBE_MAP_NEGATIVE_Y;
case 4:
return gl.TEXTURE_CUBE_MAP_POSITIVE_Z;
case 5:
return gl.TEXTURE_CUBE_MAP_NEGATIVE_Z;
}
};
const getDepthStencilAttachmentPoint = (
context: GloContext,
spec: AttachmentSpec
): GLenum => {
const { gl } = context;
const { internalFormat } = spec.texture;
switch (internalFormat) {
case gl.DEPTH_COMPONENT:
return gl.DEPTH_ATTACHMENT;
case gl.DEPTH_STENCIL:
return gl.DEPTH_STENCIL_ATTACHMENT;
default:
throw new Error(
`Depth stencil attachment cannot be a texture of internal format ${internalFormat}.`
);
}
};
const getFramebufferStatusName = (
context: GloContext,
status: GLenum
): string => {
const { gl } = context;
switch (status) {
case gl.FRAMEBUFFER_COMPLETE:
return "FRAMEBUFFER_COMPLETE";
case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
return "FRAMEBUFFER_INCOMPLETE_ATTACHMENT";
case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
return "FRAMEBUFFER_INCOMPLETE_DIMENSIONS";
case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
return "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";
case gl.FRAMEBUFFER_UNSUPPORTED:
return "FRAMEBUFFER_UNSUPPORTED";
default:
throw new Error(`Framebuffer status value ${status} is unknown.`);
}
};
<file_sep>import { Color } from "./Color";
interface Colors {
[key: string]: Color;
}
interface ColorStrings {
[key: string]: string;
}
const parseColors = (colorStrings: ColorStrings): Colors => {
const colors: Colors = {};
for (const key in colorStrings) {
colors[key] = Color.fromHexString(colorStrings[key]);
}
return colors;
};
export const COLORS = parseColors({
blue: "4071b3",
lightGreen: "abc422",
orange: "e46b1c",
white: "ffffff",
});
<file_sep>import { Vector4 } from "./Geometry/Vector4";
export const packSByte4FromVector4 = (vector: Vector4): number => {
const x = packSnorm(vector.x);
const y = packSnorm(vector.y);
const z = packSnorm(vector.z);
const w = packSnorm(vector.w);
return (w << 24) | (z << 16) | (y << 8) | x;
};
export const packSnorm = (value: number): number => {
const x = getSByteFromSnorm(value);
return x < 0 ? x + 256 : x;
};
const getSByteFromSnorm = (value: number): number => {
return Math.floor(127.5 * value);
};
<file_sep>export const createZeroArray = (count: number): number[] => {
const array: number[] = [];
for (let i = 0; i < count; i++) {
array[i] = 0;
}
return array;
};
export function flatMap<T, U>(
array: T[],
callbackfn: (value: T, index: number, array: T[]) => U[],
thisArg?: any
): U[] {
return flattenOnce(array.map(callbackfn, thisArg));
}
export function flattenOnce<T>(arrays: T[][]): T[] {
return arrays.reduce((priorValues, array) => priorValues.concat(array), []);
}
export const range = (start: number, stop: number, step: number): number[] => {
return Array.from(
{ length: (stop - start) / step + 1 },
(_, index) => step * index + start
);
};
/**
* Call a function a given number of times and return the results of every call.
*
* @param count - how many times to call the function
* @param timesFunction - the function to call
* @returns an array of return values from each call of the function
*/
export function times<T>(
count: number,
timesFunction: (index: number) => T
): T[] {
const values: T[] = [];
for (let i = 0; i < count; i++) {
const value = timesFunction(i);
values.push(value);
}
return values;
}
<file_sep>import { Point3 } from "./Point3";
export class Triangle {
/** The vertices in counterclockwise order. */
vertices: Point3[];
constructor(vertices: Point3[]) {
this.vertices = vertices;
}
}
<file_sep>export const isAlmostEqual = (
a: number,
b: number,
tolerance: number = Number.EPSILON
) => {
return Math.abs(a - b) < tolerance;
};
<file_sep>import { times } from "./Array";
export interface BinaryReader {
byteIndex: number;
dataView: DataView;
sourceData: ArrayBuffer;
textDecoder: TextDecoder;
}
export const createBinaryReader = (sourceData: ArrayBuffer): BinaryReader => {
return {
byteIndex: 0,
dataView: new DataView(sourceData),
sourceData,
textDecoder: new TextDecoder("utf-8"),
};
};
export const expect = (expectation: boolean, message: string) => {
if (!expectation) {
throw new Error(message);
}
};
export const expectBytesLeft = (
reader: BinaryReader,
byteCount: number,
message: string
) => {
if (reader.byteIndex + byteCount > reader.sourceData.byteLength) {
throw new Error(message);
}
};
export function expectIndexInBounds<T>(
index: number,
array: T[],
message: string
) {
if (index < 0 || index >= array.length) {
throw new Error(message);
}
}
export const haveReachedEndOfFile = (reader: BinaryReader): boolean => {
return reader.byteIndex === reader.sourceData.byteLength;
};
export const readFloat32Array = (
reader: BinaryReader,
count: number
): number[] => {
const bytesPerFloat32 = 4;
const sizeInBytes = bytesPerFloat32 * count;
expectBytesLeft(
reader,
sizeInBytes,
`Failed reading float32 array at byte index ${reader.byteIndex}.`
);
const values = times(count, index => {
const byteIndex = bytesPerFloat32 * index + reader.byteIndex;
return reader.dataView.getFloat32(byteIndex, true);
});
reader.byteIndex += sizeInBytes;
return values;
};
export const readString = (reader: BinaryReader, byteCount: number): string => {
expectBytesLeft(
reader,
byteCount,
`Failed reading string at byte index ${reader.byteIndex}.`
);
const start = reader.byteIndex;
const end = start + byteCount;
const uint8View = new Uint8Array(reader.sourceData.slice(start, end));
const result = reader.textDecoder.decode(uint8View);
reader.byteIndex += byteCount;
return result;
};
export const readUint16 = (reader: BinaryReader): number => {
const bytesPerUint16 = 2;
expectBytesLeft(
reader,
bytesPerUint16,
`Failed reading uint16 at byte index ${reader.byteIndex}.`
);
const value = reader.dataView.getUint16(reader.byteIndex, true);
reader.byteIndex += bytesPerUint16;
return value;
};
export const readUint16Array = (
reader: BinaryReader,
count: number
): number[] => {
const bytesPerUint16 = 2;
const sizeInBytes = bytesPerUint16 * count;
expectBytesLeft(
reader,
sizeInBytes,
`Failed reading uint16 array at byte index ${reader.byteIndex}.`
);
const values = times(count, index => {
const byteIndex = bytesPerUint16 * index + reader.byteIndex;
return reader.dataView.getUint16(byteIndex, true);
});
reader.byteIndex += sizeInBytes;
return values;
};
export const readUint32 = (reader: BinaryReader): number => {
const bytesPerUint32 = 4;
expectBytesLeft(
reader,
bytesPerUint32,
`Failed reading uint32 at byte index ${reader.byteIndex}.`
);
const value = reader.dataView.getUint32(reader.byteIndex, true);
reader.byteIndex += bytesPerUint32;
return value;
};
export const readUint8 = (reader: BinaryReader): number => {
expectBytesLeft(
reader,
1,
`Failed reading uint8 at byte index ${reader.byteIndex}.`
);
const value = reader.dataView.getUint8(reader.byteIndex);
reader.byteIndex++;
return value;
};
export const skipBytes = (reader: BinaryReader, byteCount: number) => {
expectBytesLeft(
reader,
byteCount,
`Failed skipping ${byteCount} bytes at byte index ${reader.byteIndex}.`
);
reader.byteIndex += byteCount;
};
<file_sep>import { Vector2 } from "./Geometry/Vector2";
import { limitUnitLength, clamp } from "./Clamp";
export enum Action {
Move = "MOVE",
}
export enum Axis1dDirection {
Negative = "NEGATIVE",
Positive = "POSITIVE",
}
export enum Axis2dDirection {
NegativeX = "NEGATIVE_X",
NegativeY = "NEGATIVE_Y",
PositiveX = "POSITIVE_X",
PositiveY = "POSITIVE_Y",
}
interface ButtonState {
framesDown: number;
}
interface KeyMappingAxis1d {
action: Action;
direction: Axis1dDirection;
key: KeyboardEventKey;
type: "AXIS_1D";
}
interface KeyMappingAxis2d {
action: Action;
direction: Axis2dDirection;
key: KeyboardEventKey;
type: "AXIS_2D";
}
interface KeyMappingButton {
action: Action;
key: KeyboardEventKey;
type: "BUTTON";
}
export enum KeyMappingType {
Axis1d = "AXIS_1D",
Axis2d = "AXIS_2D",
Button = "BUTTON",
}
export type KeyMapping = KeyMappingAxis1d | KeyMappingAxis2d | KeyMappingButton;
export interface InputState {
axis1dsByAction: Map<Action, number>;
axis2dsByAction: Map<Action, Vector2>;
buttonsByAction: Map<Action, ButtonState>;
isKeyDownByKey: Map<KeyboardEventKey, boolean>;
keyMappings: KeyMapping[];
pointer: {
delta: Vector2;
nextDelta: Vector2;
};
}
export enum KeyboardEventKey {
A = "a",
ArrowDown = "ArrowDown",
ArrowLeft = "ArrowLeft",
ArrowRight = "ArrowRight",
ArrowUp = "ArrowUp",
D = "d",
S = "s",
W = "w",
}
export const createInputState = (keyMappings: KeyMapping[]): InputState => {
return {
axis1dsByAction: createAxis1dsByAction(keyMappings),
axis2dsByAction: createAxis2dsByAction(keyMappings),
buttonsByAction: createButtonsByAction(keyMappings),
isKeyDownByKey: createIsKeyDownByKey(keyMappings),
keyMappings,
pointer: {
delta: Vector2.zero(),
nextDelta: Vector2.zero(),
},
};
};
export const getButtonDown = (input: InputState, action: Action): boolean => {
const button = input.buttonsByAction.get(action);
return button.framesDown > 0;
};
export const getButtonTapped = (input: InputState, action: Action): boolean => {
const button = input.buttonsByAction.get(action);
return button.framesDown === 1;
};
export const getAxis1d = (input: InputState, action: Action): number => {
return input.axis1dsByAction.get(action);
};
export const getAxis2d = (input: InputState, action: Action): Vector2 => {
return input.axis2dsByAction.get(action);
};
export const handleKeyDown = (input: InputState, eventKey: string) => {
const { isKeyDownByKey } = input;
const key = eventKey as KeyboardEventKey;
if (isKeyDownByKey.has(key)) {
isKeyDownByKey.set(key, true);
}
};
export const handleKeyUp = (input: InputState, eventKey: string) => {
const { isKeyDownByKey } = input;
const key = eventKey as KeyboardEventKey;
if (isKeyDownByKey.has(key)) {
isKeyDownByKey.set(key, false);
}
};
export const handleMouseMove = (input: InputState, delta: Vector2) => {
input.pointer.nextDelta = delta;
};
export const updateInput = (input: InputState) => {
const { keyMappings } = input;
resetInput(input);
for (const keyMapping of keyMappings) {
switch (keyMapping.type) {
case KeyMappingType.Axis1d:
updateAxis1d(input, keyMapping);
break;
case KeyMappingType.Axis2d:
updateAxis2d(input, keyMapping);
break;
case KeyMappingType.Button: {
updateButton(input, keyMapping);
break;
}
}
}
applyLimits(input);
};
const applyLimits = (input: InputState) => {
const { axis1dsByAction, axis2dsByAction } = input;
Array.from(axis1dsByAction.entries()).forEach(([action, axis]) => {
axis1dsByAction.set(action, clamp(axis, -1, 1));
});
Array.from(axis2dsByAction.entries()).forEach(([action, axis]) => {
axis2dsByAction.set(action, limitUnitLength(axis));
});
};
const createIsKeyDownByKey = (
keyMappings: KeyMapping[]
): Map<KeyboardEventKey, boolean> => {
const isKeyDownByKey = new Map<KeyboardEventKey, boolean>();
for (const keyMapping of keyMappings) {
isKeyDownByKey.set(keyMapping.key, false);
}
return isKeyDownByKey;
};
const createAxis1dsByAction = (
keyMappings: KeyMapping[]
): Map<Action, number> => {
const axis1dsByAction = new Map<Action, number>();
const axis1dKeyMappings = keyMappings.filter(
keyMapping => keyMapping.type === KeyMappingType.Axis2d
);
const mappedActions = getMappedActions(axis1dKeyMappings);
for (const action of mappedActions) {
axis1dsByAction.set(action, 0);
}
return axis1dsByAction;
};
const createAxis2dsByAction = (
keyMappings: KeyMapping[]
): Map<Action, Vector2> => {
const axis2dsByAction = new Map<Action, Vector2>();
const axis2dKeyMappings = keyMappings.filter(
keyMapping => keyMapping.type === KeyMappingType.Axis2d
);
const mappedActions = getMappedActions(axis2dKeyMappings);
for (const action of mappedActions) {
axis2dsByAction.set(action, Vector2.zero());
}
return axis2dsByAction;
};
const createButtonsByAction = (
keyMappings: KeyMapping[]
): Map<Action, ButtonState> => {
const buttonsByAction = new Map<Action, ButtonState>();
const buttonKeyMappings = keyMappings.filter(
keyMapping => keyMapping.type === KeyMappingType.Button
);
const mappedActions = getMappedActions(buttonKeyMappings);
for (const action of mappedActions) {
buttonsByAction.set(action, { framesDown: 0 });
}
return buttonsByAction;
};
const getMappedActions = (keyMappings: KeyMapping[]): Action[] => {
return Array.from(new Set(keyMappings.map(keyMapping => keyMapping.action)));
};
const getAxis2dComponent = (direction: Axis2dDirection): number => {
switch (direction) {
case Axis2dDirection.NegativeX:
case Axis2dDirection.PositiveX:
return 0;
case Axis2dDirection.NegativeY:
case Axis2dDirection.PositiveY:
return 1;
}
};
const getAxis1dSignedOne = (direction: Axis1dDirection): number => {
switch (direction) {
case Axis1dDirection.Negative:
return -1;
case Axis1dDirection.Positive:
return 1;
}
};
const getAxis2dSignedOne = (direction: Axis2dDirection): number => {
switch (direction) {
case Axis2dDirection.NegativeX:
case Axis2dDirection.NegativeY:
return -1;
case Axis2dDirection.PositiveX:
case Axis2dDirection.PositiveY:
return 1;
}
};
const resetInput = (input: InputState) => {
const { axis1dsByAction, axis2dsByAction, pointer } = input;
pointer.delta = pointer.nextDelta;
pointer.nextDelta = Vector2.zero();
Array.from(axis1dsByAction.keys()).forEach(action =>
axis1dsByAction.set(action, 0)
);
Array.from(axis2dsByAction.keys()).forEach(action =>
axis2dsByAction.set(action, Vector2.zero())
);
};
const updateAxis1d = (input: InputState, keyMapping: KeyMappingAxis1d) => {
const { axis1dsByAction, isKeyDownByKey } = input;
const { key } = keyMapping;
if (isKeyDownByKey.get(key)) {
const { action, direction } = keyMapping;
const signedOne = getAxis1dSignedOne(direction);
const axis = axis1dsByAction.get(action);
axis1dsByAction.set(action, axis + signedOne);
}
};
const updateAxis2d = (input: InputState, keyMapping: KeyMappingAxis2d) => {
const { axis2dsByAction, isKeyDownByKey } = input;
const { key } = keyMapping;
if (isKeyDownByKey.get(key)) {
const { action, direction } = keyMapping;
const component = getAxis2dComponent(direction);
const signedOne = getAxis2dSignedOne(direction);
const axis = axis2dsByAction.get(action);
axis.elements[component] += signedOne;
}
};
const updateButton = (input: InputState, keyMapping: KeyMappingButton) => {
const { buttonsByAction, isKeyDownByKey } = input;
const { action, key } = keyMapping;
const button = buttonsByAction.get(action);
if (isKeyDownByKey.get(key)) {
button.framesDown++;
} else {
button.framesDown = 0;
}
};
<file_sep>import { Bivector3 } from "./Bivector3";
import { Vector3 } from "./Vector3";
import { wedge } from "./GeometricAlgebra";
import { Quaternion } from "./Quaternion";
export class Rotor3 {
a: number;
b: Bivector3;
constructor(a: number = 0, b: Bivector3 = new Bivector3()) {
this.a = a;
this.b = b;
}
get length(): number {
return Math.sqrt(this.squaredLength);
}
get squaredLength(): number {
const a = this.a;
const b = this.b;
return a * a + b.squaredLength;
}
static fromAngleAndPlane(angle: number, plane: Bivector3): Rotor3 {
const halfAngleSin = Math.sin(angle / 2);
const a = Math.cos(angle / 2);
const b = Bivector3.multiply(-halfAngleSin, Bivector3.normalize(plane));
return new Rotor3(a, b);
}
static fromQuaternion(q: Quaternion): Rotor3 {
const a = q.w;
const b = new Bivector3([-q.z, q.y, -q.x]);
return new Rotor3(a, b);
}
static fromVector3Pair(a: Vector3, b: Vector3): Rotor3 {
const scalar = Vector3.dot(a, b) + 1;
const bivector = wedge(b, a);
return new Rotor3(scalar, bivector);
}
static identity(): Rotor3 {
return new Rotor3(1, new Bivector3([0, 0, 0]));
}
static multiply(s: Rotor3, t: Rotor3): Rotor3 {
const scalar =
s.a * t.a - s.b.xy * t.b.xy - s.b.xz * t.b.xz - s.b.yz * t.b.yz;
const bivector = new Bivector3([
s.b.xy * t.a + s.a * t.b.xy + s.b.yz * t.b.xz - s.b.xz * t.b.yz,
s.b.xz * t.a + s.a * t.b.xz - s.b.yz * t.b.xy + s.b.xy * t.b.yz,
s.b.yz * t.a + s.a * t.b.yz + s.b.xz * t.b.xy - s.b.xy * t.b.xz,
]);
return new Rotor3(scalar, bivector);
}
static normalize(rotor: Rotor3): Rotor3 {
const length = rotor.length;
return new Rotor3(rotor.a / length, Bivector3.divide(rotor.b, length));
}
static reverse(rotor: Rotor3): Rotor3 {
return new Rotor3(rotor.a, Bivector3.negate(rotor.b));
}
}
<file_sep>export class TraceError extends Error {
private source: Error;
constructor(source: Error, ...params: any[]) {
super(...params);
this.name = "TraceError";
this.source = source;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, TraceError);
}
}
toString(): string {
return super.toString() + this.source.toString();
}
}
<file_sep># Table of Contents
# S1. Blender info
# S2. File writing utilities
# S3. Blender utilities
# S4. Dawn types
# S5. Dawn scene file
# S6. Blender Addon
# S1. Blender info ************************************************************
import bpy
import math
import struct
from bpy_extras.io_utils import ExportHelper
from bpy.types import Operator
from enum import IntEnum
from mathutils import Vector, Quaternion
from typing import Iterable, List, Union
BpyContext = bpy.types.Context
BpyMesh = bpy.types.Mesh
BpyMeshLoopColorLayer = bpy.types.MeshLoopColorLayer
BpyObject = bpy.types.Object
bl_info = {
"author": "<NAME> <<EMAIL>>",
"blender": (2, 80, 0),
"category": "Import-Export",
"description": "Export .dwn files.",
"location": "File > Export > DWN",
"name": "Dawn Toolbox Scene Exporter",
"version": (1, 0, 0),
}
file_header_tag = "DWNSCENE"
file_version = 1
# S2. File writing utilities **************************************************
def pack_float_array(values: Iterable[float]) -> bytes:
float_list = [struct.pack("<f", value) for value in values]
return b"".join(float_list)
def pack_int_array(
values: Iterable[int],
bytes_per_value: int, signed: bool) -> bytes:
int_list = [
value.to_bytes(
bytes_per_value, byteorder="little", signed=signed)
for value in values]
return b"".join(int_list)
def pack_uint8_norm_array(values: Iterable[float]) -> bytes:
int_list = [math.floor(255 * value).to_bytes(
1, byteorder="little", signed=False)
for value in values]
return b"".join(int_list)
def write_float32_array(content: bytearray, values: Iterable[float]):
content.extend(pack_float_array(values))
def write_string(content: bytearray, value: str):
value_bytes = value.encode("utf-8")
content.extend(value_bytes)
def write_uint16(content: bytearray, value: int):
uint16_value = value.to_bytes(2, byteorder="little", signed=False)
content.extend(uint16_value)
def write_uint32(content: bytearray, value: int):
uint32_value = value.to_bytes(4, byteorder="little", signed=False)
content.extend(uint32_value)
def write_uint8(content: bytearray, value: int):
uint8_value = value.to_bytes(1, byteorder="little", signed=False)
content.extend(uint8_value)
# S3. Blender utilities *******************************************************
def filter_by_type(objects: List[BpyObject], type):
return [obj for obj in objects if obj.type == type]
def get_all_children_by_parent(objects: List[BpyObject]) -> dict:
children_by_parent = dict()
for obj in objects:
parent = obj.parent
children = children_by_parent[parent] if (
parent in children_by_parent) else []
children.append(obj)
children_by_parent[parent] = children
return children_by_parent
def get_quaternion_values(quaternion: Quaternion) -> List[float]:
return [quaternion.w, quaternion.x, quaternion.y, quaternion.z]
def get_indices(bpy_mesh: BpyMesh) -> List[float]:
indices: List[float] = []
for polygon in bpy_mesh.polygons:
loop_indices = [loop_index for loop_index in polygon.loop_indices]
indices.extend(loop_indices)
return indices
def pack_mesh_loop_color_layer(layer: BpyMeshLoopColorLayer) -> bytes:
interleaved_colors: List[float] = []
for loop_color in layer.data:
interleaved_colors.extend(loop_color.color)
return pack_uint8_norm_array(interleaved_colors)
def triangulate_mesh(obj: BpyObject):
import bmesh
mesh = obj.data
b = bmesh.new()
b.from_mesh(mesh)
bmesh.ops.triangulate(
b, faces=b.faces[:],
quad_method="BEAUTY", ngon_method="BEAUTY")
bmesh.ops.recalc_face_normals(b, faces=b.faces)
b.to_mesh(mesh)
b.free()
# S4. Dawn types **************************************************************
class ComponentType(IntEnum):
INVALID = 0
FLOAT32 = 1
INT8 = 2
INT16 = 3
INT32 = 4
UINT8 = 5
UINT16 = 6
UINT32 = 7
def get_size_in_bytes(self) -> int:
if self.value == ComponentType.INVALID:
return 0
elif self.value == ComponentType.FLOAT32:
return 4
elif self.value == ComponentType.INT8:
return 1
elif self.value == ComponentType.INT16:
return 2
elif self.value == ComponentType.INT32:
return 4
elif self.value == ComponentType.UINT8:
return 1
elif self.value == ComponentType.UINT16:
return 2
elif self.value == ComponentType.UINT32:
return 4
else:
return 0
def is_integer(self) -> bool:
if self.value == ComponentType.INVALID:
return False
elif self.value == ComponentType.FLOAT32:
return False
elif self.value == ComponentType.INT8:
return True
elif self.value == ComponentType.INT16:
return True
elif self.value == ComponentType.INT32:
return True
elif self.value == ComponentType.UINT8:
return True
elif self.value == ComponentType.UINT16:
return True
elif self.value == ComponentType.UINT32:
return True
else:
return False
def is_signed(self) -> bool:
if self.value == ComponentType.INVALID:
return False
elif self.value == ComponentType.FLOAT32:
return True
elif self.value == ComponentType.INT8:
return True
elif self.value == ComponentType.INT16:
return True
elif self.value == ComponentType.INT32:
return True
elif self.value == ComponentType.UINT8:
return False
elif self.value == ComponentType.UINT16:
return False
elif self.value == ComponentType.UINT32:
return False
else:
return False
class Accessor:
def __init__(self, buffer: bytearray, byte_count: int, byte_index: int,
byte_stride: int, component_count: int,
component_type: ComponentType):
self.buffer = buffer
self.byte_count = byte_count
self.byte_index = byte_index
self.byte_stride = byte_stride
self.component_count = component_count
self.component_type = component_type
class VertexAttributeType(IntEnum):
INVALID = 0
COLOR = 1
NORMAL = 2
POSITION = 3
TEXCOORD = 4
class VertexAttribute:
def __init__(self, accessor: Accessor, type: VertexAttributeType):
self.accessor = accessor
self.type = type
class VertexLayout:
def __init__(self, vertex_attributes: List[VertexAttribute]):
self.vertex_attributes = vertex_attributes
class Mesh:
def __init__(self, index_accessor: Accessor, vertex_layout: VertexLayout):
self.index_accessor = index_accessor
self.vertex_layout = vertex_layout
class ObjectType(IntEnum):
INVALID = 0
MESH = 1
class Object:
def __init__(self, content: Union[Mesh], type: ObjectType):
self.content = content
self.type = type
class Transform:
def __init__(self, orientation: Quaternion, position: Vector,
scale: Vector):
self.orientation = orientation
self.position = position
self.scale = scale
class TransformNode:
def __init__(self, obj: Object, transform: Transform):
self.children = []
self.object = obj
self.transform = transform
def set_children(self, children: List["TransformNode"]):
self.children = children
class Scene:
def __init__(self):
self.accessors = []
self.buffers = []
self.meshes = []
self.objects = []
self.transform_nodes = []
self.vertex_layouts = []
def add_accessor(self, accessor: Accessor):
self.accessors.append(accessor)
def add_buffer(self, buffer: bytearray):
self.buffers.append(buffer)
def add_mesh(self, mesh: Mesh):
self.meshes.append(mesh)
def add_object(self, obj: Object):
self.objects.append(obj)
def add_transform_node(self, transform_node: TransformNode):
self.transform_nodes.append(transform_node)
def add_vertex_layout(self, vertex_layout: VertexLayout):
self.vertex_layouts.append(vertex_layout)
# S5. Dawn scene file *********************************************************
def get_transform(obj: BpyObject) -> Transform:
return Transform(
orientation=obj.matrix_basis.to_quaternion(),
position=obj.matrix_basis.to_translation(),
scale=obj.matrix_basis.to_scale())
def pack_components(values: list, bytes_per_component: int,
component_type: ComponentType):
if component_type.is_integer():
return pack_int_array(
values, bytes_per_component, component_type.is_signed())
else:
return pack_float_array(values)
def add_accessor(scene: Scene, values: list, component_count: int,
component_type: ComponentType) -> Accessor:
bytes_per_component = component_type.get_size_in_bytes()
byte_stride = bytes_per_component * component_count
content = pack_components(values, bytes_per_component, component_type)
scene.add_buffer(content)
accessor = Accessor(buffer=content, byte_count=len(content),
byte_index=0, byte_stride=byte_stride,
component_count=component_count,
component_type=component_type)
scene.add_accessor(accessor)
return accessor
def add_vertex_layout(
scene: Scene, bpy_mesh: BpyMesh, indices: List[int]) -> VertexLayout:
positions: List[float] = []
normals: List[float] = []
for index in indices:
loop = bpy_mesh.loops[index]
vertex = bpy_mesh.vertices[loop.vertex_index]
positions.extend(vertex.co)
normals.extend(loop.normal)
position_accessor = add_accessor(
scene, positions, 3, ComponentType.FLOAT32)
normal_accessor = add_accessor(scene, normals, 3, ComponentType.FLOAT32)
attributes: List[VertexAttribute] = [
VertexAttribute(position_accessor, VertexAttributeType.POSITION),
VertexAttribute(normal_accessor, VertexAttributeType.NORMAL)
]
if bpy_mesh.vertex_colors.active is not None:
active_vertex_color_layer = bpy_mesh.vertex_colors.active
vertex_colors = pack_mesh_loop_color_layer(active_vertex_color_layer)
color_accessor = add_accessor(
scene, vertex_colors, 4, ComponentType.UINT8)
attributes.append(VertexAttribute(
color_accessor, VertexAttributeType.COLOR))
vertex_layout = VertexLayout(attributes)
scene.add_vertex_layout(vertex_layout)
return vertex_layout
def add_mesh(scene: Scene, obj: BpyObject) -> Mesh:
triangulate_mesh(obj)
bpy_mesh: BpyMesh = obj.data
bpy_mesh.calc_normals_split()
indices = get_indices(bpy_mesh)
index_accessor = add_accessor(
scene=scene, values=indices, component_count=1,
component_type=ComponentType.UINT16)
vertex_layout = add_vertex_layout(scene, bpy_mesh, indices)
mesh = Mesh(index_accessor, vertex_layout)
scene.add_mesh(mesh)
return mesh
def add_object(scene: Scene, obj: BpyObject) -> Object:
mesh = add_mesh(scene, obj)
new_object = Object(mesh, ObjectType.MESH)
scene.add_object(new_object)
return new_object
def add_transform_nodes(scene: Scene, objects: List[BpyObject]):
transform_nodes_by_object = dict()
bpy_objects_by_object = dict()
for obj in objects:
content = add_object(scene, obj)
bpy_objects_by_object[content] = obj
transform_node = TransformNode(
obj=content, transform=get_transform(obj))
transform_nodes_by_object[obj] = transform_node
scene.add_transform_node(transform_node)
children_by_parent = get_all_children_by_parent(objects)
for transform_node in scene.transform_nodes:
parent = bpy_objects_by_object[transform_node.object]
child_objects = children_by_parent.get(parent, [])
children = [transform_nodes_by_object[child]
for child in child_objects]
transform_node.set_children(children)
def get_accessor_chunk(scene: Scene) -> bytearray:
chunk = bytearray()
accessors = scene.accessors
for accessor in accessors:
write_uint32(chunk, accessor.byte_count)
write_uint32(chunk, accessor.byte_index)
write_uint16(chunk, accessor.byte_stride)
write_uint16(chunk, scene.buffers.index(accessor.buffer))
write_uint8(chunk, accessor.component_count)
write_uint8(chunk, accessor.component_type)
return chunk
def get_buffer_chunk(scene: Scene) -> bytearray:
chunk = bytearray()
buffers: List[bytearray] = scene.buffers
write_uint16(chunk, len(buffers))
for buffer in buffers:
write_uint32(chunk, len(buffer))
chunk.extend(buffer)
return chunk
def get_mesh_chunk(scene: Scene) -> bytearray:
chunk = bytearray()
meshes: List[Mesh] = scene.meshes
placeholder_material_index = 0
for mesh in meshes:
write_uint16(chunk, scene.accessors.index(mesh.index_accessor))
write_uint16(chunk, placeholder_material_index)
write_uint16(chunk, scene.vertex_layouts.index(mesh.vertex_layout))
return chunk
def get_object_chunk(scene: Scene) -> bytearray:
chunk = bytearray()
objects: List[Object] = scene.objects
for obj in objects:
write_uint16(chunk, scene.meshes.index(obj.content))
write_uint8(chunk, obj.type)
return chunk
def get_transform_node_chunk(scene: Scene) -> bytearray:
chunk = bytearray()
transform_nodes: List[TransformNode] = scene.transform_nodes
write_uint16(chunk, len(transform_nodes))
for transform_node in transform_nodes:
transform = transform_node.transform
write_float32_array(
chunk, get_quaternion_values(transform.orientation))
write_float32_array(chunk, transform.position.xyz)
write_float32_array(chunk, transform.scale.xyz)
write_uint16(chunk, scene.objects.index(transform_node.object))
write_uint16(chunk, len(transform_node.children))
for child in transform_node.children:
write_uint16(chunk, scene.transform_nodes.index(child))
return chunk
def get_vertex_layout_chunk(scene: Scene) -> bytearray:
chunk = bytearray()
vertex_layouts: List[VertexLayout] = scene.vertex_layouts
write_uint16(chunk, len(vertex_layouts))
for vertex_layout in vertex_layouts:
vertex_attributes = vertex_layout.vertex_attributes
write_uint16(chunk, len(vertex_attributes))
for vertex_attribute in vertex_attributes:
write_uint16(chunk, scene.accessors.index(
vertex_attribute.accessor))
write_uint8(chunk, vertex_attribute.type)
return chunk
def get_file_content(objects: List[BpyObject]) -> bytearray:
mesh_objects = filter_by_type(objects, "MESH")
scene = Scene()
add_transform_nodes(scene, mesh_objects)
content = bytearray()
write_chunk(content, "ACCE", get_accessor_chunk(scene))
write_chunk(content, "MESH", get_mesh_chunk(scene))
write_chunk(content, "OBJE", get_object_chunk(scene))
write_chunk(content, "TRAN", get_transform_node_chunk(scene))
write_chunk(content, "VERT", get_vertex_layout_chunk(scene))
write_chunk(content, "BUFF", get_buffer_chunk(scene))
return content
def get_file_header(content: bytearray) -> bytearray:
file_header = bytearray()
write_string(file_header, file_header_tag)
write_uint32(file_header, file_version)
write_uint32(file_header, len(content))
return file_header
def write_chunk(content: bytearray, tag: str, chunk: bytearray):
write_string(content, tag)
write_uint32(content, len(chunk))
content.extend(chunk)
def save_dwn(objects: List[BpyObject], filepath: str):
content = get_file_content(objects)
file_header = get_file_header(content)
with open(filepath, "wb") as file:
file.write(file_header)
file.write(content)
# S6. Blender Addon ***********************************************************
class OBJECT_OT_export_dwn(Operator, ExportHelper):
""".dwn file export addon"""
bl_idname = "object.export_dwn"
bl_label = "Dawn Toolbox Export"
bl_options = {"REGISTER", "UNDO"}
filename_ext = ".dwn"
filter_glob: bpy.props.StringProperty(
default="*.dwn", options={"HIDDEN"}, maxlen=255)
should_export_selected_only: bpy.props.BoolProperty(
name="Selected only", description="Export selected mesh items only",
default=True)
def execute(self, context: BpyContext):
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode="OBJECT")
objects = (context.selected_objects
if self.should_export_selected_only else
context.scene.objects)
save_dwn(objects, self.filepath)
return {"FINISHED"}
def export_menu_item_func(self, context: BpyContext):
self.layout.operator(OBJECT_OT_export_dwn.bl_idname,
text="Dawn Toolbox Export (.dwn)")
def register():
bpy.utils.register_class(OBJECT_OT_export_dwn)
bpy.types.TOPBAR_MT_file_export.append(export_menu_item_func)
def unregister():
bpy.utils.unregister_class(OBJECT_OT_export_dwn)
bpy.types.TOPBAR_MT_file_export.remove(export_menu_item_func)
if __name__ == "__main__":
register()
<file_sep>export interface Size3 {
depth: number;
height: number;
width: number;
}
<file_sep>import { isAlmostEqual } from "./Float";
export class Color {
/**
* The components in the order red, green, blue, and alpha. Each component is
* in the range [0, 1].
*/
components: number[];
constructor(components: number[] = [0, 0, 0, 0]) {
this.components = components;
}
get a(): number {
return this.components[3];
}
get b(): number {
return this.components[2];
}
get g(): number {
return this.components[1];
}
get r(): number {
return this.components[0];
}
set a(a: number) {
this.components[3] = a;
}
set b(b: number) {
this.components[2] = b;
}
set g(g: number) {
this.components[1] = g;
}
set r(r: number) {
this.components[0] = r;
}
toString(): string {
return `(${this.r}, ${this.g}, ${this.b}, ${this.a})`;
}
static fromHexString(hex: string): Color {
const integer = parseInt(hex, 16);
const alpha = hex.length === 8 ? ((integer >> 24) & 0xff) / 255 : 1;
const red = ((integer >> 16) & 0xff) / 255;
const green = ((integer >> 8) & 0xff) / 255;
const blue = (integer & 0xff) / 255;
return new Color([red, green, blue, alpha]);
}
static isAlmostEqual(a: Color, b: Color, tolerance?: number): boolean {
return a.components.every((component, index) =>
isAlmostEqual(component, b.components[index], tolerance)
);
}
static isExactlyEqual(a: Color, b: Color): boolean {
return a.components.every(
(component, index) => component === b.components[index]
);
}
static opaqueBlack(): Color {
return new Color([0, 0, 0, 1]);
}
static opaqueWhite(): Color {
return new Color([1, 1, 1, 1]);
}
static toRgbaInteger(color: Color): number {
const red = Math.floor(255 * color.r);
const green = Math.floor(255 * color.g);
const blue = Math.floor(255 * color.b);
const alpha = Math.floor(255 * color.a);
return (alpha << 24) | (blue << 16) | (green << 8) | red;
}
static transparentBlack(): Color {
return new Color([0, 0, 0, 0]);
}
}
<file_sep>import { Vector3 } from "./Vector3";
export class Point3 {
elements: number[];
constructor(elements: number[] = [0, 0, 0]) {
this.elements = elements;
}
get x(): number {
return this.elements[0];
}
get y(): number {
return this.elements[1];
}
get z(): number {
return this.elements[2];
}
set x(x: number) {
this.elements[0] = x;
}
set y(y: number) {
this.elements[1] = y;
}
set z(z: number) {
this.elements[2] = z;
}
toString(): string {
return `(${this.x}, ${this.y}, ${this.z})`;
}
static add(p: Point3, v: Vector3): Point3 {
return new Point3([p.x + v.x, p.y + v.y, p.z + v.z]);
}
static fromVector3(v: Vector3): Point3 {
return new Point3([v.x, v.y, v.z]);
}
static subtract(a: Point3, b: Point3): Vector3 {
return new Vector3([a.x - b.x, a.y - b.y, a.z - b.z]);
}
static toFloat32Array(point: Point3): Float32Array {
return new Float32Array(point.elements);
}
static zero(): Point3 {
return new Point3([0, 0, 0]);
}
}
<file_sep>export class Vector2 {
elements: number[];
constructor(elements: number[] = [0, 0]) {
this.elements = elements;
}
get length(): number {
return Math.sqrt(this.squaredLength);
}
get squaredLength(): number {
const x = this.x;
const y = this.y;
return x * x + y * y;
}
get x(): number {
return this.elements[0];
}
get y(): number {
return this.elements[1];
}
set x(x: number) {
this.elements[0] = x;
}
set y(y: number) {
this.elements[1] = y;
}
toString(): string {
return `⟨${this.x}, ${this.y}⟩`;
}
static add(a: Vector2, b: Vector2): Vector2 {
return new Vector2([a.x + b.x, a.y + b.y]);
}
static dot(a: Vector2, b: Vector2): number {
return a.x * b.x + a.y * b.y;
}
static divide(v: Vector2, s: number): Vector2 {
return new Vector2([v.x / s, v.y / s]);
}
static multiply(s: number, v: Vector2): Vector2 {
return new Vector2([s * v.x, s * v.y]);
}
static negate(v: Vector2): Vector2 {
return new Vector2([-v.x, -v.y]);
}
static normalize(v: Vector2): Vector2 {
return Vector2.divide(v, v.length);
}
static pointwiseDivide(a: Vector2, b: Vector2): Vector2 {
return new Vector2([a.x / b.x, a.y / b.y]);
}
static pointwiseMultiply(a: Vector2, b: Vector2): Vector2 {
return new Vector2([a.x * b.x, a.y * b.y]);
}
static rotate(v: Vector2, angle: number): Vector2 {
const c = Math.cos(angle);
const s = Math.sin(angle);
return new Vector2([c * v.x - s * v.y, s * v.x + c * v.y]);
}
static subtract(a: Vector2, b: Vector2): Vector2 {
return new Vector2([a.x - b.x, a.y - b.y]);
}
static zero(): Vector2 {
return new Vector2([0, 0]);
}
}
<file_sep>import { Point3 } from "./Point3";
import { Vector2 } from "./Vector2";
import { Vector4 } from "./Vector4";
import { Size3 } from "../Size3";
export class Vector3 {
elements: number[];
constructor(elements: number[] = [0, 0, 0]) {
this.elements = elements;
}
get length(): number {
return Math.sqrt(this.squaredLength);
}
get squaredLength(): number {
const x = this.x;
const y = this.y;
const z = this.z;
return x * x + y * y + z * z;
}
get x(): number {
return this.elements[0];
}
get y(): number {
return this.elements[1];
}
get z(): number {
return this.elements[2];
}
set x(x: number) {
this.elements[0] = x;
}
set y(y: number) {
this.elements[1] = y;
}
set z(z: number) {
this.elements[2] = z;
}
toString(): string {
return `⟨${this.x}, ${this.y}, ${this.z}⟩`;
}
static add(a: Vector3, b: Vector3): Vector3 {
return new Vector3([a.x + b.x, a.y + b.y, a.z + b.z]);
}
static cross(a: Vector3, b: Vector3): Vector3 {
return new Vector3([
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x,
]);
}
static dot(a: Vector3, b: Vector3): number {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
static divide(v: Vector3, s: number): Vector3 {
return new Vector3([v.x / s, v.y / s, v.z / s]);
}
static fromPoint3(point: Point3): Vector3 {
return new Vector3([point.x, point.y, point.z]);
}
static fromSize3(size: Size3): Vector3 {
return new Vector3([size.width, size.depth, size.height]);
}
static fromSphericalCoordinates(
radius: number,
inclination: number,
azimuth: number
): Vector3 {
return new Vector3([
radius * Math.sin(inclination) * Math.cos(azimuth),
radius * Math.sin(inclination) * Math.sin(azimuth),
radius * Math.cos(inclination),
]);
}
static fromVector2(vector: Vector2): Vector3 {
return new Vector3([vector.x, vector.y, 0]);
}
static fromVector4(vector: Vector4): Vector3 {
return new Vector3([vector.x, vector.y, vector.z]);
}
static multiply(s: number, v: Vector3): Vector3 {
return new Vector3([s * v.x, s * v.y, s * v.z]);
}
static negate(v: Vector3): Vector3 {
return new Vector3([-v.x, -v.y, -v.z]);
}
static normalize(v: Vector3): Vector3 {
return Vector3.divide(v, v.length);
}
static pointwiseDivide(a: Vector3, b: Vector3): Vector3 {
return new Vector3([a.x / b.x, a.y / b.y, a.z / b.z]);
}
static pointwiseMultiply(a: Vector3, b: Vector3): Vector3 {
return new Vector3([a.x * b.x, a.y * b.y, a.z * b.z]);
}
static project(a: Vector3, b: Vector3): Vector3 {
return Vector3.multiply(Vector3.dot(a, b) / b.squaredLength, b);
}
static reject(a: Vector3, b: Vector3): Vector3 {
return Vector3.subtract(b, Vector3.project(a, b));
}
static subtract(a: Vector3, b: Vector3): Vector3 {
return new Vector3([a.x - b.x, a.y - b.y, a.z - b.z]);
}
static toFloat32Array(v: Vector3): Float32Array {
return new Float32Array(v.elements);
}
static unitX(): Vector3 {
return new Vector3([1, 0, 0]);
}
static unitY(): Vector3 {
return new Vector3([0, 1, 0]);
}
static unitZ(): Vector3 {
return new Vector3([0, 0, 1]);
}
static zero(): Vector3 {
return new Vector3([0, 0, 0]);
}
}
<file_sep>import {
App,
updateFrame,
createApp,
handleResize as handleResizeWithApp,
} from "./App";
import * as Glo from "./WebGL/GloContext";
import "./Stylesheets/main.css";
import {
handleKeyDown,
handleKeyUp,
handleMouseMove as handleMouseMoveInput,
} from "./Input";
import { Vector2 } from "./Geometry/Vector2";
interface AnimationFrame {
app: App;
id: number;
}
const animateFrame = (
frame: AnimationFrame,
timestamp: DOMHighResTimeStamp
) => {
const { app } = frame;
try {
updateFrame(app);
} catch (error) {
logError(error);
displayError(error);
cancelAnimationFrame(frame.id);
return;
}
frame.id = requestAnimationFrame(timestamp => animateFrame(frame, timestamp));
};
const createEventHandlers = (app: App, canvas: HTMLCanvasElement) => {
canvas.addEventListener("click", event => handleClick(event, canvas));
document.addEventListener("keydown", event => {
handleKeyDown(app.input, event.key);
});
document.addEventListener("keyup", event => {
handleKeyUp(app.input, event.key);
});
document.addEventListener("pointerlockchange", event => {
handlePointerLockChange(event, app, canvas);
});
document.addEventListener("pointerlockerror", event => {
handlePointerLockError(event);
});
window.addEventListener("resize", event => handleResizeWithApp(event, app));
};
const displayError = (error: Error) => {
const pageErrorArea = document.getElementById("page-error-area");
pageErrorArea.style.display = "block";
const pageError = document.getElementById("page-error");
pageError.textContent = error.toString();
};
const handleClick = (event: MouseEvent, canvas: HTMLCanvasElement): any => {
canvas.requestPointerLock();
};
const handlePointerLockChange = (
event: Event,
app: App,
canvas: HTMLCanvasElement
): any => {
if (document.pointerLockElement === canvas) {
if (!app.handleMouseMove) {
const handleMouseMove = (event: MouseEvent) => {
handleMouseMoveInput(
app.input,
new Vector2([event.movementX, -event.movementY])
);
};
document.addEventListener("mousemove", handleMouseMove, false);
app.handleMouseMove = handleMouseMove;
}
} else {
if (app.handleMouseMove) {
document.removeEventListener("mousemove", app.handleMouseMove, false);
app.handleMouseMove = null;
}
}
};
const handlePointerLockError = (event: Event): any => {
const error = new Error("Failed to lock the pointer.");
displayError(error);
logError(error);
};
const logError = (error: Error) => {
console.error(error);
};
const main = () => {
const canvas = document.getElementById("canvas") as HTMLCanvasElement;
let app: App;
try {
const context = Glo.createContext(canvas);
app = createApp(context, { width: 800, height: 600 });
} catch (error) {
logError(error);
displayError(error);
return;
}
createEventHandlers(app, canvas);
const frame = {
app,
id: 0,
};
frame.id = requestAnimationFrame(timestamp => animateFrame(frame, timestamp));
};
main();
<file_sep>import { rotate } from "./GeometricAlgebra";
import { Matrix4 } from "./Matrix4";
import { Rotor3 } from "./Rotor3";
import { Vector3 } from "./Vector3";
export class Matrix3 {
rows: Vector3[];
constructor(rows: Vector3[]) {
this.rows = rows;
}
getColumn(index: number): Vector3 {
return new Vector3([
this.rows[0].elements[index],
this.rows[1].elements[index],
this.rows[2].elements[index],
]);
}
static fromMatrix4(m: Matrix4): Matrix3 {
return new Matrix3([
Vector3.fromVector4(m.rows[0]),
Vector3.fromVector4(m.rows[1]),
Vector3.fromVector4(m.rows[2]),
]);
}
static fromRotor3(rotor: Rotor3): Matrix3 {
return new Matrix3([
rotate(rotor, Vector3.unitX()),
rotate(rotor, Vector3.unitY()),
rotate(rotor, Vector3.unitZ()),
]);
}
static toFloat32Array(m: Matrix3): Float32Array {
const elements = m.rows.reduce(
(elements, row) => elements.concat(row.elements),
[] as number[]
);
return new Float32Array(elements);
}
static transpose(m: Matrix3): Matrix3 {
return new Matrix3([m.getColumn(0), m.getColumn(1), m.getColumn(2)]);
}
}
|
3c38618488429be95eb373c4434adb5c03f8ca15
|
[
"Markdown",
"Python",
"TypeScript"
] | 44
|
TypeScript
|
Vavassor/Dawn-Toolbox
|
12380acb041d2437f1fd32954867753b0cd09cd8
|
bee6f78e3adeb13c3003464571c7f0c0543f4268
|
refs/heads/master
|
<repo_name>mari8i/kitte-speaker<file_sep>/requirements.txt
flask-restful
playsound
gi
<file_sep>/kitte-upload.sh
curl -X POST -H "Content-Type: multipart/form-data" -F "file=@$2" "http://192.168.1.86/kitte/$1"
<file_sep>/kitte.py
import os.path
import os
from flask import Flask
from flask_restful import Api, Resource, reqparse
import werkzeug
from subprocess import Popen
#from playsound import playsound
class Kitte(Resource):
FILES_DIR = "/var/www/kitte/media"
PLAYER = "/usr/bin/play"
def get(self, name=None):
if not name:
files = [os.path.splitext(f)[0]
for f in os.listdir(Kitte.FILES_DIR)
if f.endswith(".mp3")]
return files, 200
path = os.path.join(Kitte.FILES_DIR, name + ".mp3")
print(path)
if not os.path.isfile(path):
return "File not found", 400
#playsound(path)
p = Popen([Kitte.PLAYER, path])
return "OK", 200
def post(self, name):
if not name:
return "No file specified", 400
parse = reqparse.RequestParser()
parse.add_argument('file', type=werkzeug.datastructures.FileStorage, location='files')
args = parse.parse_args()
audioFile = args['file']
if not audioFile:
return "No file to upload", 400
audioFile.save(os.path.join(Kitte.FILES_DIR, name + ".mp3"))
return "OK", 201
pass
app = Flask(__name__)
api = Api(app)
api.add_resource(Kitte, "/kitte/<string:name>", "/kitte/")
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/kitte.wsgi
import sys
sys.path.insert(0, '/var/www/kitte/')
from kitte import app as application<file_sep>/README.md
# kitte-speaker
The Kitte bullshit speaker
<file_sep>/kitte-list.sh
curl "http://192.168.1.86/kitte/"
<file_sep>/kitte-play.sh
curl "http://192.168.1.86/kitte/$1"
|
3b32833f81f73508b2f47924547872be740547a2
|
[
"Markdown",
"Python",
"Text",
"Shell"
] | 7
|
Text
|
mari8i/kitte-speaker
|
ea50cb658994c14a6b17719abda59ee1e2f29460
|
22990ebefa20123567bf4acd41df44623825372f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.