+ 23

JS classes

I'm interrested to create js classes. I'm doing a chess game. So, I want to create class Unit { constructor { // to initiate all placement, colors etc... of units } // something to say how a queen moves // something to say how the king moves etc... for all units... } how to do this ? if you can show me in code playground it will be better thanks https://code.sololearn.com/W55eddAsvI2x/?ref=app here is the beginning

19th Apr 2018, 9:07 AM
NoxFly
NoxFly - avatar
10 ответов
+ 4
Here is a chess game I did with all the pieces classes :) https://code.sololearn.com/Wzy1Y14DIF90/?ref=app
19th Apr 2018, 9:11 PM
clement
clement - avatar
+ 9
You've Good Idea nice
20th Apr 2018, 7:05 PM
Sadaam Linux
Sadaam Linux - avatar
+ 8
yes I know its better Nitrocell
22nd Apr 2018, 8:22 AM
NoxFly
NoxFly - avatar
+ 5
Hi NoxFly I think you maybe looking for something like this (ES6): class Rook { constructor(colour) { this.x = 0; this.y = 0; this.type=colour //Your state variables } //class methods move(direction) { // given the input directions, move the player according to the rules of the piece } rook1= new Rook("black"); rook2=new Rook("white"); rook1.move("foward"); You just to need to be careful that JS classes are really syntactic sugar on JS Functions, so private methods and data are not there (you need to use Closures). And Inheritance is not quite the same as other languages (Prototype inheritance). JS inverts the relationship between functions and classes. Classic Classes are data that carries behaviour (methods) whereas JS Functions are Behaviour that carries data.
19th Apr 2018, 11:03 AM
Mike Choy
Mike Choy - avatar
+ 5
I recommend c++ or java for games/applications.
22nd Apr 2018, 7:38 AM
Baltazarus
Baltazarus - avatar
+ 3
for ES6 code I am using the 2nd link see code: https://code.sololearn.com/WTvhHZWRgMan/ for non-ES6 code I am using method 1.2 from the 1st link see code: https://code.sololearn.com/Wvo5ljRvHuJD/
19th Apr 2018, 9:53 AM
🤖 Basile Laderchi
+ 3
20th Apr 2018, 7:31 PM
NoxFly
NoxFly - avatar
+ 2
You may want to consider using typescript to implement your js in an object oriented manner
22nd Apr 2018, 9:16 PM
Thejuice Layar
Thejuice Layar - avatar
+ 1
i am working on a pool game. i use functions to discribe how the balls should behave when they collide or bounce from a wall etc. Not exactly the same but you never know ... https://code.sololearn.com/WY734AN3TF0c/?ref=app
19th Apr 2018, 5:10 PM
davy hermans
davy hermans - avatar