menu
announcement

Spectrum is now read-only. Learn more about the decision in our official announcement.

WarriorJS

An exciting game of programming and Artificial Intelligence

Channels
Team

How do I organize my code into modules?

May 18, 2018 at 12:49am

How do I organize my code into modules?

May 18, 2018 at 12:49am (Edited 4 years ago)
Splitting your player code into modules is currently not supported in WarriorJS. However, you can easily achieve the same results with the help of Rollup.
  1. Install Rollup: npm install --global rollup
  2. In your profile directory, create a src directory
  3. Move the player code: mv Player.js src/main.js
  4. Create the modules you want inside of src and import them into main.js using ES6 import/export syntax
  5. Add the following line at the end of src/main.js: export default Player;
  6. Once you're ready to play, run: rollup src/main.js --o Player.js --f cjs
  7. This will create a Player.js file by bundling all the modules together
  8. Lastly, remove the last line in Player.js: module.exports = Player;
  9. That's it! Run warriorjs to start playing
Example:
// src/main.js
import isEmptyAhead from "./isEmptyAhead";
class Player {
playTurn(warrior) {
if (isEmptyAhead(warrior)) {
warrior.walk();
} else {
warrior.attack();
}
}
}
export default Player;
// src/isEmptyAhead.js
function isEmptyAhead(warrior) {
return warrior.feel().isEmpty();
}
export default isEmptyAhead;
Result:
// Player.js
'use strict';
function isEmptyAhead(warrior) {
return warrior.feel().isEmpty();
}
class Player {
playTurn(warrior) {
if (isEmptyAhead(warrior)) {
warrior.walk();
} else {
warrior.attack();
}
}
}
module.exports = Player; // REMOVE THIS LINE!
No messages yet