How do you restart Swift Command Line code from the beginning? - swift

I am new to swift and I am currently trying to build a basic number
guessing game using Xcode's command line tool. I have been able to complete the game but I am not able to find out how to restart the game so that the user can play again after winning or losing. Any advice?

Given that no details or code were given, i'll say you may use a loop. You probably are storing the game state in variables. When the game reaches the end, the loop should restart, restoring all game data to the initial state. If you have any doubts, read this section of the Swift documentation about control flow (it has examples with games, yay):
https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html

Felipe Borges got started but I wanted to provide a concrete example on how one might design such a game:
var playAgain = true
repeat {
print("The game starts!")
// The user plays
// Response is a game-state variable
let response = readLine()
print("The game is over yay!")
print("ask the user whether to play again?")
playAgain = false // whatever the user does goes here
} while playAgain
The two most important things to keep in mind are the loop and the game state. The game state should be scoped inside a function or loop so that the next iteration of the game starts over with new values. In my example, there are no variables pertaining to specific game states outside of the repeat {} while loop, so each iteration starts fresh (the response variable being the example here).

Related

Unity New Input System and Animations

I am creating a basic 2D fighter game and am trying to replace what was the old input system with the new input system. Because of this the old systems update would wait for buttons and then call appropriate functions when they were pressed. Movement was actually the easiest part, simply rigging a 1D Vector and then grabbing the float to use with movement, awesome. However the difficulty is in pressing keys to change things in the game. For example, I have an input 's' which should lead to the method Crouch(). This method changes the animation running and alters the hitbox to be shorter and tell the attack to use a smaller hitbox as well. A Stand() method is called on release of 's' to return everything to the way it is. I have my Player Input object set to 'Invoke Unity Events' which leads to the corresponding method needed. The problem is that even though these events are set to be push and release they are read as a toggle effect instead of press and release triggers(respectively). This does the same thing with my attack function because it forces the animation to play twice, one for pressing and one for releasing. Is there a fix for this or is this currently a bug? Edit: Here are some images to clarify and the code used to reflect everything happening associated with the Attack functionality. Let me know if anything else should be needed
public void Attack(){
anim.SetTrigger("attack");
StartCoroutine(wait());
}
IEnumerator wait(){
if(!isCrouched){
yield return new WaitForSeconds(1.3f);
SHitBox.enabled = true;
yield return new WaitForSeconds(.5f);
SHitBox.enabled = false;
}
if(isCrouched){
yield return new WaitForSeconds(1.3f);
CHitBox.enabled = true;
yield return new WaitForSeconds(.5f);
CHitBox.enabled = false;
}
}
Binding
Action
Think I figured it out. At least for the purposes of this specific thread. The answer was it was not my code. There is what I am going to call a bug in the new Unity Input System. Specifically there were three lines of code all simultaneously being hooked which caused three calls on my method. The fix was commenting out two lines of code. Here's the thread where this is solved, coincidentally found on GitHub help pages, heres the link:
https://github.com/Unity-Technologies/InputSystem/issues/959
the issue is listed as close but its still a problem for me, lol...
The only issue left is that the behavior of selecting the type of button press that I want to use is still acting funky. Mainly the inputs are still simply firing without listening to the type of input I want. I am basically just going to start searching through unity code to find where these choices have impact. If there are no comments/answers in 8 hours I'll accept my own answer because this has technically been answered, it just leads to another question.

ROBLOX Studio ScreenGui score display

How do I make a TextLabel's text update to a variable?
I have tried setting the text to "score: ", _G.score
but it won't update with the variable, and yes I do set the text after the variable has updated.
Code:
script.Parent.mouseClick:connect(function()
_G.score = _G.score + 1
game.StarterGui.ScreenGui.TextLabel.Text = _G.score
end)
game.StarterGui is actually a template GUI, and every time a player joins the game, a copy of it is made and given to the new player. Thus, if you try to modify it, you will not be actually modifying the copies of it that were given to all the players.
There are two solutions to this problem:
Only use relative paths—that being, only use paths to GUI objects that begin with "script." just like you said script.Parent.mouseClick:connect(…).
Iterate through all the copies that have been given out to the players. This can be found under each Player object's .PlayerGui.
You should almost never do the latter. Here's how you can decide:
If you have code that is found within the StarterGui (rather than in the Workspace or something), then you should use the former. This is because when the StarterGui gets copied into a new player's GUI (called a PlayerGui), that script will get copied along with it since it was inside of the StarterGui. Thus, a relative path like script.Parent.Something.SomethingElse.Text = "hi" will be valid; it will affect that PlayerGui.
If you have some code that is not within the StarterGui (like if it's in the Workspace), then you must use the latter. This is because such a script will not get copied into each player's PlayerGui. As a result, you must go through each player's PlayerGui in a for loop or something similar. This scenario is very rarely the case, and if it ever is, consider trying to make it not the case if possible because this is a very hairy situation to try to deal with; you have to account for special circumstances like the possibility that a player hasn't gotten a copy of the StarterGui yet.
Please let me know if this explanation was in any way confusing; I'll try my best to explain it better.
You can find some visuals to go along with this explanation and some further reading on the official ROBLOX Wiki's explanation of this topic here: "Player vs. Starter GUIs".

Using a timer vs update to run game SpriteKit

I am curious what to use for my game. A timer:
let goodFPS = SKAction.wait(forDuration: 0.01666)
let mainGameRunner = SKAction.run {
//my code is here
}
let toRepeat = SKAction.repeatForever(SKAction.sequence([goodFPS,mainGameRunner]))
inGameHighScore.run(toRepeat,withKey:"mainGame")
or the update function:
override func update(_ currentTime: TimeInterval){
//my code is here
}
Which provides faster more consistent updates?
note: my frame rate is in the range of 45 to 58
First I think you are taking the FPS problem the wrong way around. You cannot "force" a faster frame rate than the device can give you. If you are basing the movements in your game on the assumption that every frame will be consistent, you are doing it wrong. It's actually how they did in the early days because CPUs were so slow and the difference from one generation to the new one wasn't too bad at first. But running an old DOS game on younger hardware will be tricky because the framerate is so high that the whole game mechanic becomes unstable or simply too fast to be playable.
The concept here is to think "over time" and to scale down any action in relation with the time elapsed between two frames.
The update() method gives you that opportunity by providing the current system clock state every frame. By keeping track of the time on the last frame, you can calculate the time difference with the current frame and use that difference to scale down what you are doing.
Using a timer to get the update on a consistent frame rate is not recommended nor practical. You may be calling the update closure at a given time interval, but the code inside that closure is taking time to execute on its own, and depending on your game logic, it might even have different execution times. So maybe the pause timing is consistent, but the code running before and after that pause might not be consistent. Then what happens if you run your game on a slower CPU? The code speed will change even more, making your timing inaccurate.
Another point against using an SKAction for your game loop is simply what they are. An action is an object in memory, meany to be reused by multiple objects. If you are making a "jump" action, for example, it is recommended to store that action somewhere and to reuse the same object every time you need something that "jumps", no matter what node it is. Your game loop is meant to be executed every frame, but not by different objects. Actions are also disposable. Meaning that you can kill an action even while it's running. If you put your game loop in an action, it will probably be run by the SKScene. If you use another action on your scene it becomes a puzzle right away because there are only two ways of removing an action besides letting it come to term: removing all actions or creating the action with an identifier key and use that key to remove any action with that key. If you don't see it already, it then forces you to put identifiers on every action that will be run by the scene and remove them one by one. And them again it leave a door open for a mistake that will get rid of your game loop because, keep it in mind, actions are DISPOSABLE! Then there is also no guarantee that your action will get executed first every single frame.
Why use the update() method? Simply because it is built IN your scene. No matter what, every frame, update() gets called first. THEN, the actions get executed. You cannot flush the update() method accidentally like you can with an action. You don't have to be careful about strong/weak relationships causing memory leaks because you are referring to objects from inside a closure like you do with an action.
Suggested reads:
SKAction API reference
SKScene API reference : read about the frame processing in SpriteKit. It will help you understand how they put everything together at every frame.
I hope it makes things clearer.
I'm pretty sure that SKAction's timing facilities are based on the same game loop that is calling update.
The advantage of SKAction is that it's fire and forget for you, while using update would get awkward with setting and checking a bunch of timer variables.
I don't have a ton of experience with SpriteKit but I do have some experience making games and animations in iOS.
There is a class called CADisplayLink that fires a call to a delegate every time the screen is refreshed, this is a great way to update the screen, either in a game or in an animation, because you can know it will be called every frame and no more.
I'm not sure if SpriteKit uses that class to fire the update method, but I'm sure it uses something similar. This is usually called the run loop.
SKActions run on top of this run loop.
By creating your own run loop using a wait action, not only you're not gaining any benefits, you could be introducing inconsistencies in the way your logic is run.
Imagine that you have your wait action set to 0.01 seconds (I rounded it down for simplicity). If the screen is refreshing faster than you expect, and the action is updated every 0.009 seconds, the first time it's checked, it won't fire because there's a remaining 0.001 second on the wait command, so another 0.009 seconds will pass, and your code will be executed after 0.018 seconds, instead of your desired 0.01. Not only that, but two frames will have passed between the execution.
If you use the update function, you can know that your logic will be executed once every screen refresh, and no more.

Unity2d - Destroying Object using Destroy(gameObject) // it will destroy the object with which the script is attached to

I am Creating Unit2D game & i am new to it , where i have written code for Destroying Player Bullete when it hits to Meteorite(or enemy).
I have one Bullete PREFAB. to which Destroybullete script is attached. where i have written normal code under TRIGGER function (C# script).
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.tag == "meteorite") // have given meteorite tag to meteorite PREFAB
{
Destroy(gameObject)
}
}
I want to know is it correct way to destroy any object. because it keeps showing me msg that "Avoid destroying object to avoid data loss".
AND THE MAIN THING.
This code works well in Unity Editor ( Build Settings set to android).
But if i build and create APK of it .......... on my android mobile(redmi 1s) , it is not working.Bullete starts firing automatically ( as required) but as any bullete hits meteorite than game lags for miliseconds and bulletes stops firing....AND THE SAME CODE WORKS FINE UNDER UNITY.
DOES TO MEAN I HAVE KILLED bullete prefab for ever by writing Destroy(gameObject).
need Explanation and solution for correct way destroying objects.
The correct way to destroying objects is not destroying them :).
The msg you are getting in console inside Unity is just a warning to try avoiding destroying objects, main reason is being that Destroy and Instantiate are VERY expensive commands and they are often used a lot (like your example, instantiating every bullet then destroying it).
Reason why it works well on PC is because you have much higher processing power of hardware compared to mobile and the lag you are getting on mobile is the time it takes to finish Destroy command (or Instantiate).
The way you can avoid using Instantiating and Destroying objects is by using object pooling, it is a simple way to reuse small pool of objects.
Here is a simple way how you would implement it:
1. Instantiate let's say 5 bullets at start and hide them inside barrell or something like that.
2. Fire the first bullet from barrel and when it hits something just move it back to barrel at the end of array.
3. Keep reusing the bullets
You have good in-depth explanation about object pooling here : https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling
But you can get away with much less understanding of object pooling, if this is too long try searching online something like "Unity3D object pooling" and find simpler tuorial.

Loading Next Level

I am making a game in Unity. There are currently two levels. I count to 30 seconds, when the time becomes 0, I want to load the next level automatically. But when the next level is loaded, the game screen freezes and I cannot move anything. The function I used to load the next level follows below (this function is in a script which an empty game object which will not be destroyed when loading a new level carries):
function loadNextlvl(){
var cur_level = Application.loadedLevel;
yield WaitForSeconds(5.0);
Application.LoadLevel(cur_level + 1);
}
What should I do?
My work with Unity has been hobby-driven only, but anytime I've used Application.LoadLevel I passed it a string of the level name, rather than a pointer. I see from the API that it's overloaded to take an int as well, but maybe for testing purposes, call it by name to see if that works.
Also, you need to tell Unity the levels you're going to be using. You can do this in the Build Settings off the file menu.
Lastly, you can try using Application.levelCount to see if you're within the bounds of levels.