My son and I are trying to implement one of the fun-science.org microbit tutorials - building a "tug of war" game. Essentially, 10 presses on button A moves the sprite closer to that button and the same applies on button B. When you hit the edge of the screen, music plays and a message is scrolled on the screen before the game restarts.
We've got it fully working, but once the game has been won, it doesn't seem to reset properly. It works fine on the simulator, but not on the physical device (a microbit 2).
Once the game is won, the behaviour is erratic. It usually puts the sprite back in the middle, sometimes not, but frequently, one button doesn't work in the next game. Occasionally both stop working. In every situation, a restart fixes things.
Is there something wrong with the code? I've wondered whether the music / message is corrupting something and I need to put a wait in for it to complete. I've re-downloaded the hex file and re-flashed the microbit several times, so I think I've eliminated a corrupt code file.
Javascript version of code shown below, but it was actually built in blockly using the Microsoft MakeCode tool.
input.onButtonPressed(Button.A, function () {
sprite.change(LedSpriteProperty.X, -0.1)
})
input.onButtonPressed(Button.B, function () {
sprite.change(LedSpriteProperty.X, 0.1)
})
let sprite: game.LedSprite = null
sprite = game.createSprite(2, 3)
basic.forever(function () {
if (sprite.get(LedSpriteProperty.X) == 0) {
music.startMelody(music.builtInMelody(Melodies.Birthday), MelodyOptions.Once)
basic.showString("liverpool wins")
sprite.set(LedSpriteProperty.X, 2)
} else if (sprite.get(LedSpriteProperty.X) == 4) {
music.startMelody(music.builtInMelody(Melodies.Entertainer), MelodyOptions.Once)
basic.showString("rb leipzig wins")
sprite.set(LedSpriteProperty.X, 2)
}
})
I found it was more reliable if I did game.pause() and game.resume() while scrolling the text and playing the music at the end of the game:
input.onButtonPressed(Button.A, function () {
sprite.change(LedSpriteProperty.X, -0.1)
})
input.onButtonPressed(Button.B, function () {
sprite.change(LedSpriteProperty.X, 0.1)
})
let sprite: game.LedSprite = null
sprite = game.createSprite(2, 3)
basic.forever(function () {
if (sprite.get(LedSpriteProperty.X) == 0) {
game.pause()
music.startMelody(music.builtInMelody(Melodies.Birthday), MelodyOptions.Once)
basic.showString("liverpool wins")
game.resume()
sprite.set(LedSpriteProperty.X, 2)
} else if (sprite.get(LedSpriteProperty.X) == 4) {
game.pause()
music.startMelody(music.builtInMelody(Melodies.Entertainer), MelodyOptions.Once)
basic.showString("rb leipzig wins")
game.resume()
sprite.set(LedSpriteProperty.X, 2)
}
})
You can also take a look at the following version of the game that does not use the game rendering engine https://makecode.microbit.org/projects/tug-of-led to see if that makes a difference.
Related
I'm developing camera app right now.
I finished most of important features but the most important feature left.
I want my app auto exposure mode.
Here is my sample.
do {
try camera.lockForConfiguration()
camera.focusMode = .continuousAutoFocus
camera.exposureMode = .continuousAutoExposure
camera.unlockForConfiguration()
} catch {
return
}
I made this setting between lockForConfiguration and unlockForConfiguration.
This lead to autoexposure, however it is different from native camera app.
Also, shutter speed does not go below 1/40.
It is always 1/40 whenever it is in dark environment.(where native camera app adjust shutter speed to 1/2 or even 1)
I found the answer here (https://developer.apple.com/forums/thread/26227)
But I don't understand this answer and even how to do that...
session.beginConfiguration()
defer {
session.commitConfiguration()
}
device = AVCaptureDevice.default(.builtInDualWideCamera, for: .video, position: .back)
guard let camera = device else {
set(error: .cameraUnavailable)
status = .failed
return
}
I set AVCapturedevice in this code. Also there is a session.
The answer says don't touch sessionpreset, so I did do anything by sessionPreset.
But how can I set the avcapturedevice by activeformat..?
This is very hard to understand.
Just to check if this is work, I added this codes just below above codes.
'''
var bestFormat: AVCaptureDevice.Format?
bestFormat = device!.formats[2]
print(self.device?.formats)
do {
try camera.lockForConfiguration()
camera.focusMode = .continuousAutoFocus
camera.exposureMode = .continuousAutoExposure
camera.activeFormat = bestFormat!
// camera.setExposureModeCustom(duration: CMTime(value: 1, timescale: 500), iso: 2000)
camera.unlockForConfiguration()
} catch {
return
}
'''
I believe this does not work because camera-resolution doesn't change.
even if device!.formats[2] is low resolution for me (I checked it)
Still working on this visualization: https://ayyrickay.github.io/circulating-magazines/
I've got some good updates going, but one thing that's irking me is that, when somebody clicks on the line chart, it maintains state. For example, if I click on an issue, it runs this code to update both application state and crossfilter state
(chart) => {
chart.selectAll('circle').on('click', (selected) => {
state.circulationClicked = true
const clearFilterButton = document.getElementById('clearIssueFilterButton')
clearFilterButton.classList.remove('hide')
clearFilterButton.addEventListener('click', lineChart.unClick)
renderIssueData(selected)
samplePeriodEnd.filter(d => {
const currentIssueDate = moment.utc(selected.x)
const periodEnding = moment.utc(d)
const periodStart = moment.utc({'year': periodEnding.get('year'), 'month': periodEnding.get('month') === 5 ? 0 : 6, 'day':1})
if (currentIssueDate >= periodStart && currentIssueDate <= periodEnding) {
Object.assign(state, {currentIssueDate, periodStart, periodEnding})
return currentIssueDate >= periodStart && currentIssueDate <= periodEnding
}
})
state.totalSalesByState = salesByState.all().reduce((a, b) => ({value: {sampled_total_sales: a.value.sampled_total_sales + b.value.sampled_total_sales}}))
us1Chart.colorDomain(generateScale(salesByState))
us1Chart.customUpdate()
})
}
There's a lot going on here, but I'm frustrated because it seems like because I've overridden the default click, I've blown out some functionality that I wanted - specifically, I want the circle associated with the data point to stay in the viz.
Using the renderDataPoints method isn't right, because I only need the circle to stick around on click. I've also tried creating a moveToFront method to bring the circle to the front, but that hasn't worked for me. My problem seems to be that I'm not able to locate the circle and modify its properties in the click method itself. I get the data, but I don't get the HTML/SVG associated with the data point to modify it accordingly.
Rambly question as always, but would love some help sorting this out (and potentially getting it documented somewhere?)
I'm playing with redux-saga to create a version of the snake game in react native, and I'm not sure how to go about the game loop implementation. So far I have a working version, but it feels clunky.. the snake moves at different speeds and the game is not very smooth.
Here is what I've got so far:
function *tickSaga() {
while (true) {
yield call(updateGameSaga)
const game = yield select(getGame)
if (game.crashed)
break
yield delay(1000)
}
}
The updateGameSaga basically gets the state from the store, process some logic (finds out if the snake next move will be a crash, move to an empty tile or move to a food tile and grow) and dispatches the corresponding action for it.
I'm slightly aware of things like requestAnimationFrame which I know I should be using, but I'm not sure how to make it work within the saga (maybe I don't need too do it in the saga, hence this question).
Any ideas on how to improve the smoothness of the game loop would be welcome.
UPDATE
I've included redux-saga-ticker, which internally uses setInterval (code here) to periodically send updates to the channel.
function *tickSaga() {
const channel = Ticker(1000); // game tick every 1000ms
while (true) {
yield take(channel);
yield call(updateGameSaga);
const game = yield select(getGame)
if (game.crashed)
break
}
}
It works better now and I like the channel aproach, but I still feel requestAnimationFrame is the way to go, although I'm not yet sure on how to implement it.
How about this.
let lastTime = 0;
function *tickSaga() {
while (true) {
var time = +new Date();
var delayTime = Math.max(0, 1000 - (time - lastTime));
lastTime = time + delayTime;
yield call(updateGameSaga)
const game = yield select(getGame)
if (game.crashed)
break
yield delay(delayTime)
}
}
If you need 60 fps, replace 1000 to 16 (1000/60).
For each tick you have a correction of the interval (time - lastTime) so the ticker interval should be uniform.
I have a simple ScrollView (scrolling horizontal) with some items that each have a TouchableOpacity around them.
The onPress-method for them is just a console.log so I can see the output.
So far it works!
But I then have made a setInterval() that on each loop makes a scrollTo({x:xValue, y:0, animated:false}) on the ScrollView that increases the X-value.
This way I get like a Newsticker look and feel and it is scrolling nicely.
But when it runs, the click on each item stop working?!
I guess it has something to do with the time set for setInterval(func, time) because when I increase it to a high value it works (but ofcourse the scrolling is not nice).
So I tried made a loop-method that uses requestAnimationFrame() like below, but still nothing happens when I click on the items:
function loop(func, throttle) {
let running;
let speed = throttle || 0;
function insideLoop() {
if (running !== false) {
requestAnimationFrame(insideLoop);
speed--;
if(speed <= 0){
running = func();
speed = throttle || 0;
}
}
}
insideLoop();
}
Any ideas what I need to do?
Im trying to change the cursor on differnet actions. Essentially like panning a map.
Default: Standard pointer cursor
Shift Press: Grab Cursor
Shift + Left Click(hold/dragging): Grabbing Cursor
However, this works great until i start to move, which then my cursor jumps back to Grab instead of staying on grabbing. What am I doing wrong?
$(document).keydown(function(event){
//spacebar = 8
if (event.keyCode == 16) {
$('#mysvg').css('cursor', '-webkit-grab');
}
});
$(document).keyup(function(event){
//spacebar = 8
if (event.keyCode == 16) {
$('#mysvg').css('cursor', 'pointer');
}
});
$( "#mysvg" ).mousedown(function(event){
if (event.shiftKey) {
$('#mysvg').css('cursor', '-webkit-grabbing');
}
});
Keydown fires repeatedly in many browsers until you lift the key. I know Chrome and Firefox have this behavior. So your keydown handler is resetting the cursor.