Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 hours ago.
Improve this question
I'm currently working on implementing MCTS for a game.
I have a method called
make_move
That looks like this:
(modified to be verbose for the sake of stackoverflow)
pub fn make_move(&mut self, index: usize, player: i8) -> MoveResult {
let mut result = MoveResult::Nothing;
// If the game is finished or the spot they're trying to play on is occupied set the result to be an error
// Otherwise make the move and return the result of that move (if someone won or if nothing happened)
if self.winner != 0 || self.board[index] != 0 {
self.display();
println!("Warning! Tried playing illegal move");
result = MoveResult::Error;
} else {
self.board[index] = player;
self.move_history.push(index);
result = self.check_for_win();
}
result
}
It uses this enumerator to return the result of a move
pub enum MoveResult {
// Completed meaning the move made the game over (either by win or draw)
Completed(i8),
Error,
Nothing
}
Originally, I just had a guard clause that returned an error for the first if statement, and then returned self.check_for_win() otherwise (which is always either Nothing or Completed). I've since modified it heavily in a desperate attempt to fix this bug.
The bug I'm referring to is when I use the method
let move_result = board.make_move(index, player);
move_result is always equal to either Nothing or Completed. It is never equal to Error.
In the terminal, it will even print out that there was an error, which means the if statement was true and the else shouldn't run, but it will still only return either Nothing or Completed.
I tried to check inside the method. If there was an error, the line before I return, I printed the value of result. And it printed it was equal to Error. But when I use the method and assign the return value to a variable, which I have confirmed through println's is of type Error, the variable is either Nothing or Completed!! It magically changes despite being equal to Error at every point in the process.
I have tried rewriting this method so many times in so many ways. It never works. I've been bashing my head into my keyboard all day and it simply will not cooperate. If anyone has any idea, I'd appreciate the help.
I cannot reproduce your error:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=cc3fc00a4cc4c486fd4d76b51f8f616d
#[derive(Debug, PartialEq)]
pub enum MoveResult {
// Completed meaning the move made the game over (either by win or draw)
Completed(i8),
Error,
Nothing
}
struct Game {
winner: i8,
board: Vec<i8>,
move_history: Vec<usize>
}
impl Game {
fn new(board_size: usize) -> Self {
Game{winner: 0, board: vec![0; board_size], move_history: Vec::new()}
}
fn check_for_win(&self) -> MoveResult {
MoveResult::Nothing // dummy because I don't know the win condition
}
fn display(&self) {
// pass
}
fn make_move(&mut self, index: usize, player: i8) -> MoveResult {
let mut result = MoveResult::Nothing;
// If the game is finished or the spot they're trying to play on is occupied set the result to be an error
// Otherwise make the move and return the result of that move (if someone won or if nothing happened)
if self.winner != 0 || self.board[index] != 0 {
self.display();
println!("Warning! Tried playing illegal move");
result = MoveResult::Error;
} else {
self.board[index] = player;
self.move_history.push(index);
result = self.check_for_win();
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn make_move_returns_error_when_winner_is_not_zero() {
let mut game = Game::new(10);
game.winner = 42;
let res = game.make_move(1, 2);
assert_eq!(res, MoveResult::Error);
}
#[test]
fn make_move_returns_error_when_playing_same_position_twice() {
let mut game = Game::new(10);
let res1 = game.make_move(1, 42);
assert_eq!(res1, MoveResult::Nothing);
let res2 = game.make_move(1, 55);
assert_eq!(res2, MoveResult::Error);
}
}
Of course all sorts of weird stuff might happen in your check_for_win method, but that method shouldn't even get executed if we're in the error-branch.
Related
from backend count start form 0. and 0,1,2,3...... . For each count 10 product is showing
I have taken initially count = 0 like below
var currentCount: Int = 0
and added count perameter in JSON like below in service call: but here always shows only 10 products in collectionview... even if there are more products then also not showing.. why?
fileprivate func serviceCall(){
self.currentCount+=0
let param = ["jsonrpc": "2.0",
"params": ["type" : type, "count": currentCount]] as [String : Any]
APIReqeustManager.sharedInstance.serviceCall(param: param, vc: self, url: getUrl(of: .productByFeature), header: header) {(responseData) in
if self.currentCount > 0 {
self.viewmoreDB?.result?.products! += ViewMoreBase(dictionary: responseData.dict as NSDictionary? ?? NSDictionary())?.result?.products ?? [ViewMoreProducts]()
}
else{
self.viewmoreDB = ViewMoreBase(dictionary: responseData.dict as NSDictionary? ?? NSDictionary())
}
self.productsData = self.viewmoreDB?.result?.products
self.collectionView.reloadData()
}
}
and trying to use pagination like below at the end of the collectionview activity indicator is showing but if there are more products then also not loading
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == collectionView{
if (scrollView.contentOffset.y + scrollView.frame.size.height) == scrollView.contentSize.height {
serviceCall()
}
}
}
please do help
It could be any of may issues. One of the possible things is that you do not update currentCount when you get the data and your statement if self.currentCount > 0 always fails and the else part executes which means that data is not added but overwritten and you again have just one page of data.
If this is true you are probably missing currentCount = self.productsData.count or even better, you should simply make your currentCount as a computed property doing
var currentCount: Int { productsData?.count ?? 0 }
Since this is a guess a more appropriate answer is that you need to improve your skills when debugging. One of the widely used feature which is available in most modern IDEs is using breakpoints. In most IDEs you simply click left of the line you wish to put your breakpoint and an icon shows there. When your code executes with debugger it will stop at a breakpoint and you will be able to see all the information that is currently in the stack and you will be able to execute line by line to see what is going on. So in your case you could place a breakpoint at a first line after serviceCall and see which path the code takes you and why.
If using Xcode there is another feature that you can use WHILE stopped on breakpoint. You can use console on your bottom right of your IDE to print out values as chunks of code. So while stopped there you could enter "po self.currentCount" and you could see the count. More interesting would be to see things like "ViewMoreBase(dictionary: responseData.dict as NSDictionary? ?? NSDictionary())?.result?.products" to check if you get any products from the backend.
I am trying to write a function in CAPL that takes a signal and calculates the physical value with the signal value, the signal factor and the signal offset.
This is how a simple gateway normally works:
message CAN1.myMessage1 myMessage1 = {DIR = RX};//message from the database
message CAN2.myMessage2 myMessage2 = {DIR = TX};//another message from the database
on message CAN1.*
{
if(this.id == myMessage1.id)
{
myMessage1 = this;
myMessage2.mySignalB = myMessage1.mySignalA * myMessage1.mySignalA.factor + myMessage1.mySignalA.offset;
}
}
And this is what I am trying to do:
...
on message CAN1.*
{
if(this.id ==myMessage1.id)
{
myMessage1 = this;
myMessage2.mySignalB = PhysicalValue(myMessage1.mySignalA);
}
}
double PhysicalValue(signal * s)
{
return s*s.factor+s.offset;
}
There are two problems with this code:
Firstly when I pass the signal as the parameter the compiler says that the types don't match. The second problem is that inside the function the attributes (factor and offset) are no longer recognized.
These problems might have something to do with the weird object-oriented-but-not-really nature of CAPL. The value of the signals can be accessed directly but it also has attributes?
int rawValue = myMessage1.mySignalA;
If you are familiar with C you might say that the problem is that I am specifying a pointer in the function but that I am not passing a pointer into it. But in CAPL there are no pointers and the * simply means anything.
Without the * I would have needed to use a specific signal which would have defeated the purpose of the function.
EDIT:
I have found the attribute .phys by now which does exactly what my demo function would have done.
double physValue = myMessage1.mySignalA.phys;
This has already made my code much shorter but there are other operations that I need to perform for multiple signals so being able to use signals as a function parameter would still be useful.
What you can do is this:
double PhysicalValue(signal * s)
{
// access signal by prepending a $
return $s.phys;
}
Call like this
on message CAN1.*
{
if(this.id ==myMessage1.id)
{
myMessage1 = this;
myMessage2.mySignalB = PhysicalValue(CAN1::myMessage1::mySignalA);
}
}
I.e. when you call your function, you have to provide the qualified name of the signal (with colons rather than dots). To my knowledge it is not possible to use myMessage1.mySignalA, since signals itself are not a CAPL datatype.
Apart from this, you might re-think whether you really should be using on message, but rather switch to on signal. Handling the signal values no matter with which message they are sent is done by CANoe's signal server.
Note that CANoe already has a function which does exactly what you're trying to do (multiplying by factor and adding offset). It's called getSignal:
on message CAN1.*
{
if(this.id == myMessage1.id)
{
myMessage2.mySignalB = getSignal(myMessage1::mySignalA);
}
}
Offsets and factors are defined in e.g. the DBC files.
currently I am doing
var adnetCustomerModel = customersList.find((adnetCustomerModel) => {
return adnetCustomerModel.getId() == customerId;
})
but wasting CPU cycles as I have to continue and traverse the entire list (or so I am assuming that's what happens).
I'd like to quit on first find.
Now I know I can do a filter().first() (which I believe will have same waste of CPU cycles) but is there a better way?
If it was a normal for loop I would just break...
will the return achieve the same effect in immutable.js?
tx for reading,
Sean
Immutable’s find() already returns only the first value for which the predicate returns true. It actually just wraps around the findEntry() method that’s implemented like this:
findEntry(predicate, context, notSetValue) {
var found = notSetValue;
this.__iterate((v, k, c) => {
if (predicate.call(context, v, k, c)) {
found = [k, v];
return false;
}
});
return found;
}
So, you’re not wasting any cycles. :)
Vanilla JavaScript Array.prototype.find() also returns the value of the first element to match the predicate.
SKAction has waiting for duration abilities, for a period of time on a node. And seems to perform actions on nodes. Like moveTo, etc.
If I don't want that, rather I'd prefer to call functions within GameScene after a period of time, how do I do that with SpriteKit in the GameScene, not on a Sprite or other Node?
Are SKActions the way to do this? The only way to do this?
Yes. This question IS that ridiculously simple. I lack the heuristics and terminology to find an answer. Just keep looping around on how SKAction waits are calls on SKSprites for things like scale, rotation, etc, after time. Which isn't want I want/need.
Update:
Desired outcome, inside GameScene
doSetupStuff() // does some stuff...
waitForAWhile() // somehow wait, perhaps do somethings in here, while waiting
doSomethingElse() // does this after the waitForAWhile has waited
UPDATE 2:
What I think happens, again, inside didMove(to view...)
func wait(){
let timeToPause = SKAction.wait(forDuration: 3)
run(timeToPause)
}
let wontwait = SKAction.wait(forDuration: 3)
run(wontwait)
thisFunction(willnot: WAIT"it starts immediately")
wait()
thisFunction(forcedToWait: "for wait()'s nested action to complete")
UPDATE 3:
Found a way to get the delay without using SKActions. It's a little crude and brutal, but makes more sense to me than SKActions, so far:
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
print("I waited ten seconds before printing this!")
}
An option, as you cited, is to manage this externally. The way I typically manage this sort of thing is to have an externally run update cycle. One that
To drive this updater, you could use either CADisplayLink (which is what I use right now with my OpenGL renderer) or a dispatch source timer (which I have used with my SpriteKit engine). When you use an updated, you want to calculate the delta time. The tick handler could look something like:
func tickHandler() {
let currTime = NSDate().timeIntervalSince1970
let dt = lastTime - currTime // lastTime is a data member of the class
// Call all updaters here, pretend "updater" is a known updater class
updater.update(dt)
}
And updater's update method would look something like:
func update(deltaTime:NSTimeInterval) {
// Do your magic
}
I typically have a main overall updater running independent of what people are calling scenes. Example usage would be something like having an attract mode like in old school arcade games. There they show title screen, sample game play, high scores, rinse and repeat. Scenes would be title, game play, high score. Here you can your main updater manage the time and coordinate the construction/destruction/switching of the scenes. Note this implies having an overall scene manager (which is actually quite handy to have).
For your case, you could use this updater to drive the GameScene updater. It's updater could look something like:
func update(deltaTime:NSTimeInterval) {
switch state {
case .SetupState:
// noop?
println("I'm in setup") // Shown just so you can see there is a setup state
case .WaitState:
waitTime += deltaTime
if waitTime >= kWaitTime {
// Do whats you gots to do
doSomethingElse()
state = .NextState
}
case .NextState:
// blah blah blah blah
}
}
So the flow to do this call path from your driver (CADisplayLink or dispatch source) would be something like:
tickHandler -> master updater -> game scene updater
Some will def find this is perhaps a little heavy handed. I, on the other hand, find this very helpful. While there is obviously some time management and the loss of being able to fire and forget, it can help provide more control for orchestrating pieces, as well as arbitrarily changing state without having to worry about killing already queued actions. There is also nothing that says you still cannot mix SKAction. When I did use SpriteKit, I did all my updating this way along with some dispatched items. I only used SKAction to update hierarchy. Keep in mind that I used my own animation and physics system. So at least for me I had a lot less dependency on SpriteKit (it effectively was just a renderer for me).
Note you have to have your own means to handle pause and coming to foreground where your timer will need to be resynced (you only need to worry about tickHandler). Breakpoints also will cause time jumps.
You can use below function
#define ANIM_TIME 2
SKAction *customACtion = [SKAction customActionWithDuration: ANIM_TIME actionBlock:^(SKNode *node, CGFloat elapsedTime) {
// Do Something Here
}];
Another way to make something happen after a certain period of time is to make use of the 'current time' parm passed to update(). The following code will spawn a boss at intervals ranging from 20 to 30 seconds.
In your property definitions:
var timeOfLastBoss: CFTimeInterval = -1 //Indicate no boss yet
var timePerBoss = CFTimeInterval()
.
.
.
didMoveToView() {
...
timePerBoss = CFTimeInterval(Int.random(20...30))
'''
}
.
.
.
func update(currentTime: CFTimeInterval) {
...
spawnBossForUpdate(currentTime)
...
}
'
'
'
func spawnBossForUpdate(currentTime : CFTimeInterval) {
if ( timeOfLastBoss == -1 ) {timeOfLastBoss = currentTime}
if (currentTime - timeOfLastBoss < timePerBoss) {return}
// Rest of 'spawnBoss code
self.timePerBoss = CFTimeInterval(Int.random(20...30))
self.timeOfLastBoss = currentTime
}
One way, using SKActions, in Swift 3.0, looks like this:
DEFINE: aPatientlyWaitingFunction() at the top level of
GameScene class.
To cause a delay to happen before calling the above function, inside
didMove(to view...)
three ways I've found to do this using Actions:
All three ways seem to accomplish the exact same thing:
let timeToWait: TimeInterval = 3 // is seconds in SKAction thinking time
let waitSomeTime = SKAction.wait(forDuration: timeToWait)
// 1st way __________________________________________
// with a completion handler, the function can be called after Action
run(waitSomeTime) {self.aPatientlyWaitingFunction()}
// 2nd way __________________________________________
// as a completion to be done after action, in the run invocation:
run(waitSomeTime, completion: aPatientlyWaitingFunction)
// 3rd way __________________________________________
// alternatively, as part of a sequence of actions...
// Create a sequence, by making a run action from waitSomeTime and...
let thenDoThis = SKAction.run(aPatientlyWaitingFunction)
// then activate sequence, which does one action, then the next
run(SKAction.sequence([waitSomeTime, thenDoThis]))
// OR... for something different ____________________
////////////////////////////////////////////////////////
DispatchQueue.main.asyncAfter(deadline: .now() + timeToWait) {
self.aPatientlyWaitingFunction()
print("DispatchQueue waited for 3 seconds")
}
Actually I've parsed a website using htmlparser and I would like to find a specific value inside the parsed object, for example, a string "$199", and keep tracking that element(by periodic parsing) to see the value is still "$199" or has changed.
And after some painful stupid searching using my eyes, I found the that string is located at somewhere like this:
price = handler.dom[3].children[3].children[3].children[5].children[1].
children[3].children[3].children[5].children[0].children[0].raw;
So I'd like to know whether there are methods which are less painful? Thanks!
A tree based recursive search would probably be easiest to get the node you're interested in.
I've not used htmlparser and the documentation seems a little thin, so this is just an example to get you started and is not tested:
function getElement(el,val) {
if (el.children && el.children.length > 0) {
for (var i = 0, l = el.children.length; i<l; i++) {
var r = getElement(el.children[i],val);
if (r) return r;
}
} else {
if (el.raw == val) {
return el;
}
}
return null;
}
Call getElement(handler.dom[3],'$199') and it'll go through all the children recursively until it finds an element without an children and then compares it's raw value with '$199'. Note this is a straight comparison, you might want to swap this for a regexp or similar?