Skip to content

Instantly share code, notes, and snippets.

@jonahwilliams
Created June 7, 2020 17:47
Show Gist options
  • Save jonahwilliams/3972d60de5fbf222a06582ef3b131a41 to your computer and use it in GitHub Desktop.
Save jonahwilliams/3972d60de5fbf222a06582ef3b131a41 to your computer and use it in GitHub Desktop.
Baby game
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
final entities = <Entity>[];
void main() {
GameBinding();
}
class GameBinding extends BindingBase with SchedulerBinding, ServicesBinding {
@override
void initInstances() {
super.initInstances();
RawKeyboard.instance.addListener(pending.add);
scheduleFrameCallback(gameLoop);
}
final pending = <RawKeyEvent>[];
final entities = <Entity>[
Entity(),
];
void gameLoop(Duration duration) {
var recorder = PictureRecorder();
var canvas = Canvas(recorder);
var playerMovement = normalizeEvents(pending);
for (var i = 0; i < entities.length; i++) {
var entity = entities[i];
entity.move(playerMovement);
entity.draw(canvas);
}
pending.clear();
var picture = recorder.endRecording();
var sceneBuilder = SceneBuilder();
sceneBuilder.addPicture(Offset.zero, picture);
window.render(sceneBuilder.build());
scheduleFrameCallback(gameLoop);
}
}
/// Normalize a stack of keyboard events into a single offset.
Offset normalizeEvents(List<RawKeyEvent> events) {
var xOffset = 0.0;
var yOffset = 0.0;
for (var i = 0; i < events.length; i++) {
var event = events[i];
switch (event.logicalKey.keyId) {
// A
case 97:
xOffset -= 5;
break;
// D
case 100:
xOffset += 5;
break;
// S
case 115:
yOffset += 5;
break;
// W
case 119:
yOffset -= 5;
break;
}
}
return Offset(xOffset, yOffset);
}
final paint = Paint()
..color = Color.fromRGBO(125, 125, 125, 1)
..style = PaintingStyle.fill;
class Entity {
double xPosition = 0;
double yPosition = 0;
double zPosition = 0;
double velocity = 1;
bool isPlayer = true;
void move(Offset offset) {
if (!isPlayer) {
return;
}
var dx = offset.dx;
var dy = offset.dy;
xPosition += dx;
yPosition += dy;
}
void draw(Canvas canvas) {
canvas.drawRect(Rect.fromLTWH(xPosition, yPosition, 25, 25), paint);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment