Running two loops simultaneously for a game - C - c

I'm making a game in C for my programming class, and I have to place a time countdown on the game, but I can't make it work right, because if a put a countdown function and a delay(1000), it works for the countdown, but doesn't work for the game , because it makes wait the 1s every move.
My code so far is
while(tempo > 0)
{
tempo_na_tela(&tempo);
contador_tempo(&tempo);
if(kbhit())
{
mover_refem(getch(), p_refem, &refem.px, &refem.py,
numero_inimigos_na_tela(n, in1));
}
mover_inimigo(n, p_terrorista, in1);
}
The function tempo_na_tela(..) puts the string of time on the screen, the contador_tempo(..) is the countdown, the mover_refem(...) is the function to move the game character, and the mover_inimigo(..)is a function that randomly moves the enemy in the screen.
I need to place the tempo_na_tela and the contador_tempo functions in one loop, that run simultaneously with the other loop, that run the moving functions.
How can I do it?

You're experimenting a XY problem i think.
You don't need to run simultaneously thoses 2 functions. What you're trying to accomplish is a game loop, it's very common in video-games, especially early ones.
Ask yourself, when do you need to re-paint your elements ? The answer is probably after having updated all of your data (Time, ennemy position, and having logged your player's movement)
So, you don't need simultaneous looping (ie thread i would have suggested, even if it's not true simultaneous, but that's another story.)
Instead, you can stick with one loop, but you have to do something in this fashion :
while (game_not_ended())
{
update_data();
repaint_data();
}
I hope you'll take the time to reconsider your code and the scope of your issue.

Related

How to make loops play while something else is playing

Im making a game right now where one of the characters has a fire ability. i have a loop for the attack but not the fire... How can i make a loop that runs the fire while it still attacks?
You can use the spawn function to run multiple loops at the same time.
For example :
task.spawn(function()
- your code here
end)

How would I make a lua stop an if loop inside a while true loop?

This is a pretty hard question to ask because I can't possibly fit everything into a question but I can explain the problem. My game logic/game script is essentially:
function game()
-- stuff
end
while true do
while players < 2 do
-- tell player to invite more players and all that jazz
end
if players >= 2 then
game()
end
end
(this is just pseudocode, I'm ignoring things like wait() and Roblox API for simplicity because the idea is still the same but I think the question is general enough for programming in general)
Now, in my 'game' function, when players are ready ( i.e aren't in a menu etc.) it will teleport all the ready players to a point where the game is. Unfortunately, since 'game()' is run all the time, the players keep getting teleported over and over and it doesn't stop. I'm not sure how to make is so that it only ever teleports them once even if 'game()' is constantly run.
Here is the code for the teleportation explained simply without needing knowledge of Roblox API:
if #ready >= 2 then -- if the players in the list 'ready' (the players that are ready to start the game)
print(player.Name .. " moved") -- show which player is moved
player:MoveTo(--place where the game is)) -- actually move the player
end
The problem is that since 'game()' is being run all the time, the players are constantly moved to where the game is (making it impossible for them to move). How would I get Lua to stop moving the players after all the players are moved? I tried using a for loop but that also kept being repeated since 'game()' is being repeated. I hope this is understandable to anybody knowledgeable in Lua.
It seems to me that you want to be maintaining two lists: currently playing, and wishing to play.
I'm not sure exactly what logic you're going for (can people join an in-progress game?), but the basic idea is that you'd only run game on the list of players that wish to play, not the players currently playing.

Timer to represent AI reaction times

I'm creating a card game in pygame for my college project, and a large aspect of the game is how the game's AI reacts to the current situation. I have a function to randomly generate a number within 2 parameters, and this is how long I want the program to wait.
All of the code on my ai is contained within an if statement, and once called I want the program to wait generated amount of time, and then make it's decision on what to do.
Originally I had:
pygame.time.delay(calcAISpeed(AIspeed))
This would work well, if it didn't pause the rest of the program whilst the AI is waiting, stopping the user from interacting with the program. This means I cannot use while loops to create my timer either.
What is the best way to work around this without going into multi-threading or other complex solutions? My project is due in soon and I don't want to make massive changes. I've tried using pygame.time.Clock functions to compare the current time to the generated one, but resetting the clock once the operation has been performed has proved troublesome.
Thanks for the help and I look forward to your input.
The easiest way around this would be to have a variable within your AI called something like "wait" and set it to a random number (of course it will have to be tweaked to your program speed... I'll explain in the code below.). Then in your update function have a conditional that waits to see if that wait number is zero or below, and if not subtract a certain amount of time from it. Below is a basic set of code to explain this...
class AI(object):
def __init__(self):
#put the stuff you want in your ai in here
self.currentwait = 100
#^^^ All you need is this variable defined somewhere
#If you want a static number as your wait time add this variable
self.wait = 100 #Your number here
def updateAI(self):
#If the wait number is less than zero then do stuff
if self.currentwait <= 0:
#Do your AI stuff here
else:
#Based on your game's tick speed and how long you want
#your AI to wait you can change the amount removed from
#your "current wait" variable
self.currentwait -= 100 #Your number here
To give you an idea of what is going on above, you have a variable called currentwait. This variable describes the time left the program has to wait. If this number is greater than 0, there is still time to wait, so nothing will get executed. However, time will be subtracted from this variable so every tick there is less time to wait. You can control this rate by using the clock tick rate. For example, if you clock rate is set to 60, then you can make the program wait 1 second by setting currentwait to 60 and taking 1 off every tick until the number reaches zero.
Like I said this is very basic so you will probably have to change it to fit your program slightly, but it should do the trick. Hope this helps you and good luck with your project :)
The other option is to create a timer event on the event queue and listen for it in the event loop: How can I detect if the user has double-clicked in pygame?

How to fix movement in my snake program?

I'm programming now a snake program. I have a little problem in the movement. My direction buttons are the 'W' 'A' 'S' 'D' buttons.
I have a direction variable, wich type is char. I read a button from keyboard, direction gets a value, and the snake makes one step from the 4 directions, if I hit one from WASD and then enter. I'd like to fix the enter problem.
I want, that my snake moves continually, and doesn't wait for the enter.
I'd like to make a timer for direction that way, if I don't hit a character in X milliseconds, then the snake continues to move in the direction of the last value of direction.
How to make this timer? Or any other idea?
It depends on the language you are programming in :-).
Eg. if you have a sleep() or delay() function available, you don't need any special timers and a simple infinite loop will do the job.
The important thing is how you are reading the keyboard. You can read buttons as they are pressed (non-blocking) or waiting for them till they are pressed (blocking). In your case you are reading whole lines - this is why it waits for the enter.
Not sure what is your programming language, but this pseudo-code could explain it a bit. The keyPressed() and readKey() are some fictive library function, which you need to find in your language.
while (true) {
if (keyPressed()) {
direction = readKey();
}
move(direction);
sleep(1);
}
Unfortunately, without knowing the language and if an SDK like SDL, XNA, Monogame, etc. are used we can't help. I would suggest trying to search for handling keyboard events. In XNA while the game is running it calls Draw, Update, and Event. Usually the keyboard event would be handled like so:
//...
public void Update()
{
if(Keyboard.GetStates().IsKeyDown(Keys.W))
{
Player.ChangeDirection(Direction.UP);
}
//...
Player.Move();
}
Player.ChangeDirection(Direction) may will change how the snake moves. The movement is done in the Player.Move() command every time.
EDIT: In C++ are you using any SDKs like SDL, Allegro, DirectX or that?

Implementing pacman in c, ghost movement

I am creating a pacman in c and currently I am usisng a single thread for each ghost and each ghost represents a '#' but when I run it all the screen gets full of ghosts and not all the ghosts move just one or two.
Im using this logic
create a struct of 5 ghost, each ghost contains the x,y position.
create an array of 5 threads and each thread implements one ghost
each ghost moves randomly on the screen, for each space that it moves I print
a space in the old position and then I print a '#' in the new position.
Could you provide me please an example of how to implement the movement of the ghost,
or the implementation Im doing is the correct way?
Thank you
One thread per agent is not a very common approach to building games. It quickly becomes unworkable for large scenes. The conventional solution is to define a state machine representing a ghost, with some kind of "advance" method that gives it a chance to adjust its internal state to the next time quantum. Create multiple instances of this state machine, and call all their "advance" methods on each iteration of the game loop. All of this can happen in a single thread.
There's quite a bit more to it than this, but it'll get you started.
Trying to update the screen simultaneously from several threads requires a mutex around the screen update code.

Resources