Chess.qml 21.7 KB
Newer Older
1
2
/* GCompris - chess.qml
 *
3
 * Copyright (C) 2015 Bruno Coudoin <bruno.coudoin@gcompris.net>
4
5
 *
 * Authors:
6
7
 *   Bruno Coudoin <bruno.coudoin@gcompris.net> (GTK+ version)
 *   Bruno Coudoin <bruno.coudoin@gcompris.net> (Qt Quick port)
Timothée Giet's avatar
Timothée Giet committed
8
 *   Timothée Giet <animtim@gmail.com> (big layout refactoring)
9
10
11
12
13
14
15
16
17
18
19
20
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
21
 *   along with this program; if not, see <https://www.gnu.org/licenses/>.
22
 */
23
24
25
import QtQuick 2.6
import QtQuick.Controls 1.5
import QtQuick.Controls.Styles 1.4
26
27
28
import GCompris 1.0

import "../../core"
29
import "."
30
31
32
33
34
import "chess.js" as Activity

ActivityBase {
    id: activity

35
    property bool acceptClick: true
36
    property bool twoPlayers: false
37
    property bool displayTakenPiecesButton: true
Timothée Giet's avatar
Timothée Giet committed
38
    property int coordsOpacity: 1
39
    property int movesCount: 0
40
41
    // difficultyByLevel means that at level 1 computer is bad better at last level
    property bool difficultyByLevel: true
42
    property var fen: [
43
44
45
46
47
        ["initial state", "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 1 1"],
        ["initial state", "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 1 1"],
        ["initial state", "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 1 1"],
        ["initial state", "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 1 1"],
        ["initial state", "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 1 1"]
48
    ]
49

50
51
52
    onStart: focus = true
    onStop: {}

Bruno Coudoin's avatar
Bruno Coudoin committed
53
    pageComponent: Image {
54
55
        id: background
        anchors.fill: parent
Timothée Giet's avatar
Timothée Giet committed
56
        source: Activity.url + 'background-wood.svg'
57
58
59
60
61
62
63
64
65
66
67
68
        signal start
        signal stop

        Component.onCompleted: {
            activity.start.connect(start)
            activity.stop.connect(stop)
        }

        // Add here the QML items you need to access in javascript
        QtObject {
            id: items
            property Item main: activity.main
Timothée Giet's avatar
Timothée Giet committed
69
            property GCSfx audioEffects: activity.audioEffects
70
71
72
            property alias background: background
            property alias bar: bar
            property alias bonus: bonus
Timothée Giet's avatar
Timothée Giet committed
73
            property var barHeightAddon: ApplicationSettings.isBarHidden ? textMessage.height : bar.height
74
            property bool isPortrait: (background.height >= background.width)
Timothée Giet's avatar
Timothée Giet committed
75
            property int cellSize: boardBg.width * 0.1
76
            property var fen: activity.fen
77
            property bool twoPlayer: activity.twoPlayers
78
            property bool difficultyByLevel: activity.difficultyByLevel
79
80
            property var positions
            property var pieces: pieces
81
            property var squares: squares
82
            property var history
Bruno Coudoin's avatar
Bruno Coudoin committed
83
84
            property var redo_stack
            property alias redoTimer: redoTimer
85
            property int from
86
            property bool blackTurn
87
            property bool gameOver
88
            property string message
89
            property bool isWarningMessage
90
            property alias trigComputerMove: trigComputerMove
91
92
            property alias whiteTakenPieceModel: whiteTakenPieces.takenPiecesModel
            property alias blackTakenPieceModel: blackTakenPieces.takenPiecesModel
93
94

            Behavior on cellSize { PropertyAnimation { easing.type: Easing.InOutQuad; duration: 1000 } }
95
96
97
98
99
        }

        onStart: { Activity.start(items) }
        onStop: { Activity.stop() }

Timothée Giet's avatar
Timothée Giet committed
100
101
102
103
        GCText {
            id: textMessage
            z: 20
            color: items.isWarningMessage ? "red" : "white"
104
            anchors.horizontalCenter: parent.horizontalCenter
Timothée Giet's avatar
Timothée Giet committed
105
106
107
108
109
110
111
112
113
114
115
116
117
            anchors.top: parent.top
            width: layoutArea.width
            fontSize: smallSize
            text: items.message
            horizontalAlignment: Text.AlignHCenter
            wrapMode: TextEdit.WordWrap
        }

        Grid {
            id: controls
            z: 20
            spacing: (boardBg.width - buttonSize * 4) * 0.25
            columns: items.isPortrait ? 4 : 1
118
119
            horizontalItemAlignment: Grid.AlignHCenter
            verticalItemAlignment: Grid.AlignVCenter
Timothée Giet's avatar
Timothée Giet committed
120
            property int buttonSize: undo.width
121

Timothée Giet's avatar
Timothée Giet committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
            Button {
                id: undo
                height: 30 * ApplicationInfo.ratio
                width: height
                text: "";
                style: GCButtonStyle { theme: "noStyle" }
                onClicked: {
                    Activity.undo()
                    if(whiteTakenPieces.pushedLast[whiteTakenPieces.pushedLast.length-1] == movesCount) {
                        whiteTakenPieces.pushedLast.pop()
                        whiteTakenPieces.takenPiecesModel.remove(whiteTakenPieces.takenPiecesModel.count-1)
                    }
                    if(!items.twoPlayer) {
                        movesCount--
                    }
                    if(blackTakenPieces.pushedLast[blackTakenPieces.pushedLast.length-1] == movesCount) {
                        blackTakenPieces.pushedLast.pop()
                        blackTakenPieces.takenPiecesModel.remove(blackTakenPieces.takenPiecesModel.count-1)
                    }
                    movesCount--
142
                }
Timothée Giet's avatar
Timothée Giet committed
143
144
145
146
147
148
149
150
                enabled: items.history.length > 0 ? 1 : 0
                opacity: enabled
                Image {
                    source: Activity.url + 'undo.svg'
                    height: parent.height
                    width: height
                    sourceSize.height: height
                    fillMode: Image.PreserveAspectFit
Bruno Coudoin's avatar
Bruno Coudoin committed
151
                }
Timothée Giet's avatar
Timothée Giet committed
152
153
154
155
                Behavior on opacity {
                    PropertyAnimation {
                        easing.type: Easing.InQuad
                        duration: 200
156
                    }
Timothée Giet's avatar
Timothée Giet committed
157
158
                }
            }
159

Timothée Giet's avatar
Timothée Giet committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
            Button {
                id: redo
                height: undo.height
                width: undo.height
                text: "";
                style: GCButtonStyle { theme: "noStyle" }
                onClicked: {
                    if (!twoPlayers) {
                        acceptClick = false;
                        Activity.redo()
                    } else {
                        Activity.redo()
                    }
                }
                enabled: items.redo_stack.length > 0 && acceptClick ? 1 : 0
                opacity: enabled
                Image {
                    source: Activity.url + 'redo.svg'
                    height: parent.height
                    width: height
                    sourceSize.height: height
                    fillMode: Image.PreserveAspectFit
                }
                Behavior on opacity {
                    PropertyAnimation {
                        easing.type: Easing.InQuad
                        duration: 200
Bruno Coudoin's avatar
Bruno Coudoin committed
187
                    }
Timothée Giet's avatar
Timothée Giet committed
188
189
                }
            }
Bruno Coudoin's avatar
Bruno Coudoin committed
190

Timothée Giet's avatar
Timothée Giet committed
191
192
193
194
195
196
            Button {
                id: drawerButton
                height: 30 * ApplicationInfo.ratio
                width: height
                text: "";
                style: GCButtonStyle { theme: "noStyle" }
197

Timothée Giet's avatar
Timothée Giet committed
198
199
200
201
                onClicked: {
                    whiteTakenPieces.open = !whiteTakenPieces.open
                    blackTakenPieces.open = !blackTakenPieces.open
                }
202

Timothée Giet's avatar
Timothée Giet committed
203
204
205
206
207
208
209
210
211
212
213
214
215
                enabled: displayTakenPiecesButton
                opacity: enabled
                Image {
                    source: Activity.url + 'captured.svg'
                    height: parent.height
                    width: height
                    sourceSize.height: height
                    fillMode: Image.PreserveAspectFit
                }
                Behavior on opacity {
                    PropertyAnimation {
                        easing.type: Easing.InQuad
                        duration: 200
216
                    }
Timothée Giet's avatar
Timothée Giet committed
217
218
                }
            }
219

Timothée Giet's avatar
Timothée Giet committed
220
221
222
223
224
225
226
227
228
229
230
231
232
            Button {
                height: undo.height
                width: undo.height
                text: "";
                style: GCButtonStyle { theme: "noStyle" }
                enabled: items.twoPlayer
                opacity: enabled
                Image {
                    source: Activity.url + 'turn.svg'
                    height: parent.height
                    width: height
                    sourceSize.height: height
                    fillMode: Image.PreserveAspectFit
233
                }
Timothée Giet's avatar
Timothée Giet committed
234
                onClicked: chessboard.swap()
235
            }
Timothée Giet's avatar
Timothée Giet committed
236
        }
237

Timothée Giet's avatar
Timothée Giet committed
238
239
240
241
242
243
244
        Rectangle {
            id: layoutArea
            width: background.width
            height: background.height - textMessage.height - items.barHeightAddon * 1.1
            opacity: 0
            anchors.horizontalCenter: background.horizontalCenter
        }
245

246
247
248
249
250
251
252
253
254
        Rectangle {
            id: controlsArea
            anchors.left: background.left
            anchors.right: boardBg.left
            anchors.top: boardBg.top
            anchors.bottom: boardBg.bottom
            opacity: 0
        }

Timothée Giet's avatar
Timothée Giet committed
255
256
        states: [
            State {
257
                name: "portraitLayout"; when: items.isPortrait
Timothée Giet's avatar
Timothée Giet committed
258
259
260
261
262
263
264
265
266
267
268
                PropertyChanges {
                    target: layoutArea
                    width: background.width * 0.86
                    height: background.height - textMessage.height - bar.height * 1.1 - controls.height
                }
                PropertyChanges {
                    target: controls
                    width:layoutArea.width
                    height: controls.buttonSize * 1.2
                    anchors.leftMargin: controls.spacing * 0.5
                    anchors.topMargin: 0
269
                    anchors.horizontalCenterOffset: 0
Timothée Giet's avatar
Timothée Giet committed
270
271
272
273
274
275
276
277
                }
                AnchorChanges {
                    target: layoutArea
                    anchors.top: controls.bottom
                }
                AnchorChanges {
                    target: controls
                    anchors.top: textMessage.bottom
278
                    anchors.horizontalCenter: undefined
Timothée Giet's avatar
Timothée Giet committed
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
                    anchors.left: boardBg.left
                }
            },
            State {
                name: "horizontalLayout"; when: !items.isPortrait
                PropertyChanges {
                    target: layoutArea
                    width: background.width
                    height: background.height - textMessage.height - items.barHeightAddon * 1.1
                }
                PropertyChanges {
                    target: controls
                    width: controls.buttonSize * 1.2
                    height: layoutArea.height
                    anchors.leftMargin: 0
                    anchors.topMargin: controls.spacing * 0.5
295
                    anchors.horizontalCenterOffset: items.cellSize * 0.8
Timothée Giet's avatar
Timothée Giet committed
296
297
298
299
300
301
302
                }
                AnchorChanges {
                    target: layoutArea
                    anchors.top: textMessage.bottom
                }
                AnchorChanges {
                    target: controls
303
304
                    anchors.top: controlsArea.top
                    anchors.horizontalCenter: controlsArea.horizontalCenter
Timothée Giet's avatar
Timothée Giet committed
305
306
307
308
                    anchors.left: undefined
                }
            }
        ]
309

Timothée Giet's avatar
Timothée Giet committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
        Rectangle {
            id: boardBg
            width: Math.min(layoutArea.width, layoutArea.height)
            height: boardBg.width
            anchors.centerIn: layoutArea
            z: 08
            color: "#452501"

            // The chessboard
            GridView {
                id: chessboard
                cellWidth: items.cellSize
                cellHeight: items.cellSize
                width: items.cellSize * 8
                height: chessboard.width
                interactive: false
                keyNavigationWraps: true
                model: 64
                layoutDirection: Qt.RightToLeft
                delegate: square
                rotation: 180
                z: 10
                anchors.centerIn: boardBg

                Component {
                    id: square
                    Image {
                        source: index % 2 + (Math.floor(index / 8) % 2) == 1 ?
                        Activity.url + 'chess-white.svg' : Activity.url + 'chess-black.svg';
                        width: items.cellSize
                        height: items.cellSize
Johnny Jazeix's avatar
Johnny Jazeix committed
341
                    }
Timothée Giet's avatar
Timothée Giet committed
342
                }
343

Timothée Giet's avatar
Timothée Giet committed
344
                Behavior on rotation { PropertyAnimation { easing.type: Easing.InOutQuad; duration: 1400 } }
345

Timothée Giet's avatar
Timothée Giet committed
346
347
348
349
350
351
                function swap() {
                    items.audioEffects.play('qrc:/gcompris/src/core/resource/sounds/flip.wav')
                    coordsOpacity = 0
                    timerSwap.start()
                    if(chessboard.rotation == 180)
                        chessboard.rotation = 0
Johnny Jazeix's avatar
Johnny Jazeix committed
352
353
                        else
                            chessboard.rotation = 180
354
                }
Timothée Giet's avatar
Timothée Giet committed
355
            }
356

Timothée Giet's avatar
Timothée Giet committed
357
358
359
360
361
362
363
            Timer {
                id: timerSwap
                interval: 1500
                running: false
                repeat: false
                onTriggered: coordsOpacity = 1
            }
364

Timothée Giet's avatar
Timothée Giet committed
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
            Item {
                id: letters
                anchors.left: chessboard.left
                anchors.top: chessboard.bottom
                opacity: coordsOpacity
                Behavior on opacity { PropertyAnimation { easing.type: Easing.InOutQuad; duration: 500} }
                Repeater {
                    id: lettersA
                    model: chessboard.rotation == 0 ? ["F", "G", "F", "E", "D", "C", "B", "A"] : ["A", "B", "C", "D", "E", "F", "G", "H"]
                    GCText {
                        x: items.cellSize * (index % 8) + (items.cellSize/2-width/2)
                        y: items.cellSize * Math.floor(index / 8)
                        text: modelData
                        color: "#CBAE7B"
                        font.pointSize: NaN
                        font.pixelSize: items.cellSize * 0.5
Johnny Jazeix's avatar
Johnny Jazeix committed
381
382
                    }
                }
Timothée Giet's avatar
Timothée Giet committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
            }
            Item {
                id: numbers
                anchors.left: chessboard.right
                anchors.top: chessboard.top
                opacity: coordsOpacity
                Behavior on opacity { PropertyAnimation { easing.type: Easing.InOutQuad; duration: 500} }
                Repeater {
                    model: chessboard.rotation == 0 ? ["1", "2", "3", "4", "5", "6", "7", "8"] : ["8", "7", "6", "5", "4", "3", "2", "1"]
                    GCText {
                        x: items.cellSize * Math.floor(index / 8) + width
                        y: items.cellSize * (index % 8) + (items.cellSize/2-height/2)
                        text: modelData
                        color: "#CBAE7B"
                        font.pointSize: NaN
                        font.pixelSize: items.cellSize * 0.5
Johnny Jazeix's avatar
Johnny Jazeix committed
399
                    }
400
                }
Timothée Giet's avatar
Timothée Giet committed
401
            }
402

Timothée Giet's avatar
Timothée Giet committed
403
404
405
406
407
408
409
410
411
            Rectangle {
                id: boardBorder
                width: items.cellSize * 10
                height: boardBorder.width
                anchors.centerIn: boardBg
                z: -1
                color: "#542D0F"
                border.color: "#3A1F0A"
                border.width: items.cellSize * 0.1
412
413
414
            }
        }

415
416
417
418
419
420
421
422
423
424
425
        Repeater {
            id: squares
            model: items.positions
            delegate: square
            parent: chessboard

            DropArea {
                id: square
                x: items.cellSize * (7 - pos % 8) + spacing / 2
                y: items.cellSize * Math.floor(pos / 8) + spacing / 2
                width: items.cellSize - spacing
Timothée Giet's avatar
Timothée Giet committed
426
                height: square.width
427
428
429
430
431
432
433
434
                z: 1
                keys: acceptMove ? ['acceptMe'] : ['sorryNo']
                property bool acceptMove : false
                property int pos: modelData.pos
                property int spacing: 6 * ApplicationInfo.ratio
                Rectangle {
                    id: possibleMove
                    anchors.fill: parent
Timothée Giet's avatar
Timothée Giet committed
435
                    color: parent.containsDrag ? '#803ACAFF' : 'transparent'
436
                    border.width: parent.acceptMove ? 5 : 0
Timothée Giet's avatar
Timothée Giet committed
437
                    border.color: '#FF808080'
438
439
440
441
442
443
444
445
446
447
448
449
450
                    z: 1
                }
            }

            function getSquareAt(pos) {
                for(var i=0; i < squares.count; i++) {
                    if(squares.itemAt(i).pos === pos)
                        return squares.itemAt(i)
                }
                return(undefined)
            }
        }

451
452
453
454
455
456
457
458
459
460
        Repeater {
            id: pieces
            model: items.positions
            delegate: piece
            parent: chessboard

            Piece {
                id: piece
                sourceSize.width: items.cellSize
                width: items.cellSize - spacing
Timothée Giet's avatar
Timothée Giet committed
461
                height: piece.width
462
                source: img ? Activity.url + img + '.svg' : ''
Bruno Coudoin's avatar
Bruno Coudoin committed
463
                img: modelData.img
464
465
                x: items.cellSize * (7 - pos % 8) + spacing / 2
                y: items.cellSize * Math.floor(pos / 8) + spacing / 2
466
                z: 1
467
468
                pos: modelData.pos
                newPos: modelData.pos
469
                rotation: -chessboard.rotation
470
471
472

                property int spacing: 6 * ApplicationInfo.ratio

473
474
475
476
                Drag.active: dragArea.drag.active
                Drag.hotSpot.x: width / 2
                Drag.hotSpot.y: height / 2

477
                MouseArea {
478
                    id: dragArea
479
                    anchors.fill: parent
480
481
482
                    enabled: !items.gameOver && !items.trigComputerMove.running
                    drag.target: ((items.blackTurn && !parent.isWhite) || (!items.blackTurn && parent.isWhite)) ?
                                parent : null
483
484
485
                    onPressed: {
                        piece.Drag.keys = ['acceptMe']
                        parent.z = 100
486
487
488
489
                        if(parent.isWhite == 1 && !items.blackTurn ||
                                parent.isWhite == 0 && items.blackTurn) {
                            items.from = parent.newPos
                            Activity.showPossibleMoves(items.from)
490
                        } else if(items.from != -1 && squares.getSquareAt(parent.newPos)['acceptMove']) {
491
                            Activity.moveTo(items.from, parent.newPos)
492
493
                        }
                    }
494
                    onReleased: {
495
496
                        // If no target or move not possible, we reset the position
                        if(!piece.Drag.target || (items.from != -1 && !Activity.moveTo(items.from, piece.Drag.target.pos))) {
497
498
                            var pos = parent.pos
                            // Force recalc of the old x,y position
499
                            parent.pos = -1
500
501
502
                            pieces.getPieceAt(pos).move(pos)
                        }
                    }
503
504
                }
            }
505
506

            function moveTo(from, to) {
507
                movesCount ++
508
509
                var fromPiece = getPieceAt(from)
                var toPiece = getPieceAt(to)
510
                if(toPiece.img !== '') {
Bruno Coudoin's avatar
Bruno Coudoin committed
511
                    items.audioEffects.play('qrc:/gcompris/src/core/resource/sounds/smudge.wav')
512
513
514
515
516
517
518
519
                    if(toPiece.isWhite) {
                        whiteTakenPieces.takenPiecesModel.append(toPiece)
                        whiteTakenPieces.pushedLast.push(movesCount)
                    } else {
                        blackTakenPieces.takenPiecesModel.append(toPiece)
                        blackTakenPieces.pushedLast.push(movesCount)
                    }
                }
Bruno Coudoin's avatar
Bruno Coudoin committed
520
521
                else
                    items.audioEffects.play('qrc:/gcompris/src/core/resource/sounds/scroll.wav')
522
                toPiece.hide(from)
523
                fromPiece.move(to)
524
525
            }

526
527
528
529
530
            function promotion(to) {
                var toPiece = getPieceAt(to)
                toPiece.promotion()
            }

531
532
            function getPieceAt(pos) {
                for(var i=0; i < pieces.count; i++) {
533
                    if(pieces.itemAt(i).newPos === pos)
534
535
536
537
                        return pieces.itemAt(i)
                }
                return(undefined)
            }
538
539
        }

540
541
542
543
544
545
546
        Timer {
            id: trigComputerMove
            repeat: false
            interval: 400
            onTriggered: Activity.randomMove()
        }

Bruno Coudoin's avatar
Bruno Coudoin committed
547
548
549
550
551
        // Use to redo the computer move after the user move
        Timer {
            id: redoTimer
            repeat: false
            interval: 400
552
553
554
555
            onTriggered: {
                acceptClick = true;
                Activity.moveByEngine(move)
            }
Bruno Coudoin's avatar
Bruno Coudoin committed
556
557
558
559
560
561
562
563
            property var move

            function moveByEngine(engineMove) {
                move = engineMove
                redoTimer.start()
            }
        }

564
565
        TakenPiecesList {
            id: whiteTakenPieces
566
            openWidth: items.cellSize * 0.8
567
568
569
570
            edge: false
        }
        TakenPiecesList {
            id: blackTakenPieces
571
            openWidth: items.cellSize * 0.8
572
573
574
            edge: true
        }

575
576
577
578
579
580
581
        DialogHelp {
            id: dialogHelp
            onClose: home()
        }

        Bar {
            id: bar
Bruno Coudoin's avatar
Bruno Coudoin committed
582
            content: BarEnumContent { value: help | home | (items.twoPlayer ? 0 : level) |
583
584
                                             (items.twoPlayer && !items.gameOver ? 0 : reload) }

585
586
587
588
589
590
            onHelpClicked: {
                displayDialog(dialogHelp)
            }
            onPreviousLevelClicked: Activity.previousLevel()
            onNextLevelClicked: Activity.nextLevel()
            onHomeClicked: activity.home()
591
592
593
594
            onReloadClicked: {
                trigComputerMove.stop()
                Activity.initLevel()
            }
595
596
597
598
599
600
601
602
        }

        Bonus {
            id: bonus
        }
    }

}