Skip to content

Гиззатуллин Урал #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 29 additions & 33 deletions src/TaskQueue.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,34 @@
const TaskQueue = function() {
function TaskQueue() {
function runNextTask(taskQueue) {
if (taskQueue.running || taskQueue.tasks.length === 0) {
return;
}
taskQueue.running = true;
const task = taskQueue.tasks.shift();

if (task.runAndContinue) {
setTimeout(() => {
task.runAndContinue(() => {
task.dispose && task.dispose();
taskQueue.running = false;

setTimeout(() => {
runNextTask(taskQueue);
});
});
}, 0);
}
else {
runNextTask(taskQueue);
}
}

export default class TaskQueue {
constructor() {
this.tasks = [];
this.running = false;
}

TaskQueue.prototype.push = function(run, dispose, duration) {
push(run, dispose, duration) {
if (duration === undefined || duration === null) {
this.tasks.push({runAndContinue: run, dispose});
} else {
Expand All @@ -21,35 +45,7 @@ const TaskQueue = function() {
runNextTask(this);
};

TaskQueue.prototype.continueWith = function(action) {
continueWith (action) {
this.push(action, null, 0);
};

function runNextTask(taskQueue) {
if (taskQueue.running || taskQueue.tasks.length === 0) {
return;
}
taskQueue.running = true;
const task = taskQueue.tasks.shift();

if (task.runAndContinue) {
setTimeout(() => {
task.runAndContinue(() => {
task.dispose && task.dispose();
taskQueue.running = false;

setTimeout(() => {
runNextTask(taskQueue);
});
});
}, 0);
}
else {
runNextTask(taskQueue);
}
}

return TaskQueue;
}();

export default TaskQueue;
};
280 changes: 267 additions & 13 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,40 +27,294 @@ function getCreatureDescription(card) {
return 'Существо';
}

//3.1 Создай новый тип Creature и унаследуй его от Card.
class Creature extends Card {
constructor(name, maxPower) {
super(name, maxPower);
this._currentPower = maxPower;
}

get currentPower() {
return this._currentPower;
}

// Основа для утки.
function Duck() {
this.quacks = function () { console.log('quack') };
this.swims = function () { console.log('float: both;') };
set currentPower(value) {
this._currentPower = value > this.maxPower ? this.maxPower : value;
}
//3.0 «Утка или собака?»
//3.3
getDescriptions() {
return [getCreatureDescription(this), ...super.getDescriptions()];
}
}

// Основа для утки.
//3.2 Duck наследовались от Creature.
class Duck extends Creature {
constructor() {
super('Мирная утка', 2); //2. Duck с именем «Мирная утка» и силой 2
}

quacks() {
console.log('quack');
};

swims() {
console.log('float: both;');
};
}

// Основа для собаки.
function Dog() {
//3.2 Dog наследовались от Creature.
class Dog extends Creature {
constructor() {
super('Пес-бандит', 3); //2. Dog с именем «Пес-бандит» и силой 3
}
}

// 4.1 Добавь карту Trasher: называется Громила, сила 5, наследуется от Dog.
class Trasher extends Dog {
constructor() {
super('Громила',5);
}
// 4.2 если Громилу атакуют, то он получает на 1 меньше урона.
modifyTakenDamage(value, fromCard, gameContext, continuation) {
this.view.signalAbility(() =>
super.modifyTakenDamage(value - 1, fromCard, gameContext, continuation));
}

getDescriptions() {
return ["Получает на 1 меньше урона", super.getDescriptions()];
}
}

//5.1 Добавь карту Gatling
class Gatling extends Creature {
constructor(name = 'Гатлинг', maxPower = 6) {
super(name, maxPower);
}
//5.2 переопредели метод attack так, чтобы урон наносился всем картам противника
//список карт противника можно получить через gameContext.oppositePlayer.table
//в качестве примера выполнения действий над несколькими картами можешь использовать applyCards из Player.js
attack(gameContext, continuation) {
const taskQueue = new TaskQueue();

const {currentPlayer, oppositePlayer, position, updateView} = gameContext;
taskQueue.push(onDone => this.view.showAttack(onDone));
oppositePlayer.table.forEach(card => {
taskQueue.push(onDone => {
if (card) {
this.dealDamageToCreature(2, card, gameContext, onDone);
}
});
});
taskQueue.continueWith(continuation);
};

getDescriptions() {
let descriptions = super.getDescriptions();
descriptions.push('Наносит 2 урона всем противникам');
return descriptions;
}
}

//6 Реализация карты Lad
class Lad extends Dog {
static getInGameCount() { return this.inGameCount || 0; }
static setInGameCount(value) { this.inGameCount = value; }
static getBonus() { return this.getInGameCount() * (this.getInGameCount() + 1) / 2; }
constructor() {
super('Браток', 2);
}

doAfterComingIntoPlay(gameContext, continuation) {
Lad.setInGameCount(Lad.getInGameCount() + 1);
continuation();
}

doBeforeRemoving(continuation) {
Lad.setInGameCount(Lad.getInGameCount() - 1);
continuation();
}

modifyDealedDamageToCreature(value, toCard, gameContext, continuation) {
continuation(value + Lad.getBonus());
}

modifyTakenDamage(value, fromCard, gameContext, continuation) {
continuation(value - Lad.getBonus());
}

getDescriptions() {
let descriptions = super.getDescriptions();
if (Lad.prototype.hasOwnProperty("modifyDealedDamageToCreature") && Lad.prototype.hasOwnProperty("modifyTakenDamage")) {
descriptions.push("Чем их больше, тем они сильнее");
}
return descriptions;
}
}

//7* Реализация карты Rogue
class Rogue extends Creature {
static properties = [
'modifyDealedDamageToCreature',
'modifyDealedDamageToPlayer',
'modifyTakenDamage',
];

constructor() {
super('Изгой',2);
}

doBeforeAttack(gameContext, continuation) {
const {currentPlayer, oppositePlayer, position, updateView} = gameContext;
const oppositeCard = oppositePlayer.table[position];
const obj = Object.getPrototypeOf(oppositeCard);

// Колода Шерифа, нижнего игрока.
Rogue.properties.forEach(property => {
if (obj.hasOwnProperty(property)) {
this[property] = obj[property];
delete obj[property];
}
});
continuation();
updateView();
}

getDescriptions() {
let descriptions = super.getDescriptions();
descriptions.push('Крадет способности');
return descriptions;
}
}

//8* Реализация карты Brewer
class Brewer extends Duck {
constructor(name = "Пивовар", maxPower = 2) {
super(name, maxPower);
}

doBeforeAttack(gameContext, continuation) {
let taskQueue = new TaskQueue();
const cards = gameContext.currentPlayer.table.concat(gameContext.oppositePlayer.table);

for(let card of cards.filter(card => isDuck(card))) {
card.view.signalHeal();
card.maxPower += 1;
card.currentPower += 2;
card.updateView();
}

taskQueue.continueWith(continuation);

}

getDescriptions() {
let descriptions = super.getDescriptions();
descriptions.push('Раздает живительное пиво');
return descriptions;
}
}

//9* Реализация карты PseudoDuck
class PseudoDuck extends Dog {
constructor() {
super("Псевдоутка", 3);
}
swims() {}
quacks() {}
}

//10* Реализация карты Nemo
class Nemo extends Creature {
constructor() {
super('Немо', 4);
}

modifyDealedDamageToCreature(value, toCard, gameContext, continuation) {
Object.setPrototypeOf(this, Object.getPrototypeOf(toCard));
this.doBeforeAttack(gameContext, continuation);
gameContext.updateView();
}

getDescriptions() {
let descriptions = super.getDescriptions();
descriptions.push('The one without a name without an honest heart as compass');
return descriptions;
}
}

//Колоды для проверки:
/*
const seriffStartDeck = [
new Card('Мирный житель', 2),
new Card('Мирный житель', 2),
new Card('Мирный житель', 2),
new Duck(),
new Duck(),
new Duck(),
new Gatling(),
new Rogue(),
new Brewer(),
new Nemo(),
];
const banditStartDeck = [
new Dog(),
];

// Колода Бандита, верхнего игрока.
const banditStartDeck = [
new Card('Бандит', 3),
new Trasher(),
];

const banditStartDeck = [
new Trasher(),
new Dog(),
new Dog(),
];

const banditStartDeck = [
new Lad(),
new Lad(),
];

const banditStartDeck = [
new Lad(),
new Lad(),
new Lad(),
];

const banditStartDeck = [
new Dog(),
new Dog(),
new Dog(),
new Dog(),
];

const banditStartDeck = [
new Dog(),
new PseudoDuck(),
new Dog(),
];

const banditStartDeck = [
new Brewer(),
new Brewer(),
];
*/


const seriffStartDeck = [
new Nemo(),
];
const banditStartDeck = [
new Brewer(),
new Brewer(),
];

// Создание игры.
const game = new Game(seriffStartDeck, banditStartDeck);

// Глобальный объект, позволяющий управлять скоростью всех анимаций.
SpeedRate.set(1);
SpeedRate.set(3);

// Запуск игры.
game.play(false, (winner) => {
alert('Победил ' + winner.name);
});
});