-
Notifications
You must be signed in to change notification settings - Fork 5
Example Snake
Stephen Quan edited this page Jan 16, 2023
·
2 revisions
import QtQuick
import QtQuick.Controls
Page {
id: game
property point pt: Qt.point(10, 10)
property point dir: Qt.point(1, 0)
property int cellSize: 20
property int w: 20
property int h: 20
focus: true
property list<point> moves: [ ]
property list<point> body: [ ]
Repeater {
model: body
Rectangle {
x: modelData.x * cellSize
y: modelData.y * cellSize
width: cellSize
height: cellSize
color: "orange"
}
}
Rectangle {
x: pt.x * cellSize
y: pt.y * cellSize
width: cellSize
height: cellSize
color: "red"
}
Timer {
repeat: true
running: game.activeFocus
interval: 500
onTriggered: move()
}
Frame {
visible: !game.activeFocus
anchors.centerIn: parent
Text {
text: qsTr("Click to Continue")
}
}
MouseArea {
anchors.fill: parent
onClicked: parent.forceActiveFocus()
}
function move() {
if (moves.length > 0) dir = moves.shift();
body.push(pt);
if (body.length > 10) body.shift();
pt.x = Math.min(Math.max(pt.x + dir.x, 0), w);
pt.y = Math.min(Math.max(pt.y + dir.y, 0), h);
}
Keys.onLeftPressed: moves.push(Qt.point(-1, 0))
Keys.onRightPressed: moves.push(Qt.point(1, 0))
Keys.onUpPressed: moves.push(Qt.point(0, -1))
Keys.onDownPressed: moves.push(Qt.point(0, 1))
}
You can Try it Online!