2014-12-30 17:32:57

Hello everyone!
;Tell me please, I have to shoot the enemy, one shot is to use all the supplies. ;Please tell me how to do this timer.

2014-12-31 20:16:06

Hello,
This is really unclear, but I think what you are looking for is an event queue.
It looks like:

"""
This Scheduler is quite easy. There are only two calls you need to know about, tick and schedule.
Here is an example:

import time
#Our little framerate (better to use something a little more advanced, but this works just fine.
fps = 0.03

def hello(name):
    #Just a random little function that prints 'hello name'
    print("hello %s" % name)

#There is one argument that goes in Scheduler, it is the amount you wished each time to be multiplied by. Pygame for example, ticks in incraments of 1000 each second where as time.sleep is in incraments of 1 for 1 second.
#Default is 1.0, for pygame it would be 0.001.

c = Scheduler()
c.schedule(function=hello, delay=1, repeats=2, before_delay=True, name="Fred")

while c.events:
    c.tick(fps)
    time.sleep(fps)
"""

class Scheduler:
    """Call tick to run a tick and schedular to add an event to a queue"""

    def __init__(self, time_format=1):
        self.events = set()
        self.time_format = time_format


    def tick(self, elapsed_time):
        """Call this each iteration of the game loop with an argument of the amount of time that has elapsed in seconds"""
        done_events = []
        for event in self.events:
            if event.should_run():
                event.run()
            if event.done:
                done_events.append(event)
            event.tick(elapsed_time*self.time_format)
        [self.events.remove(e) for e in done_events]

    def schedule(self, function, delay=0, repeats=1, before_delay=False, *args, **kwargs):
        """function is the name of the function that will run without the (), delay is the amount of time to wait, repeats is the amount of times the event will run (0) for infinent, and the wrest are arguments for the function"""
        e = EventMaker(function, delay, repeats, before_delay, *args, **kwargs)
        self.events.add(e)

class EventMaker:
    """This class is the event. It has all the functions to run the event."""
    def __init__(self, function, delay, repeats, before_delay, *args, **kwargs):
        self.function = function
        self.delay = delay
        self.repeats = repeats
        self.before_delay = before_delay
        self.args = args
        self.kwargs = kwargs

        #Our operation variables:
        self.elapsed_time = 0
        self.done = False

    def tick(self, elapsed_time):
        """adds time to the elapsed_time"""
        self.elapsed_time += elapsed_time

    def should_run(self):
        """Checks if the event should run"""
        if self.before_delay and not self.elapsed_time and self.repeats:
            self.repeats += 1
            return True
        elif self.elapsed_time >= self.delay:
            return True

    def run(self):
        """Runs the event"""
        self.repeats -= 1
        if self.repeats or not self.before_delay:
            self.function(*self.args, **self.kwargs)
        if self.repeats == 0:
            self.done = True
        self.elapsed_time = 0


if __name__ == '__main__':
    def hello(name):
        print("hello %s" % name)

    c = Scheduler(0.001)
    c.schedule(hello, 1, 2, True, name="Fred")

    import pygame
    pygame.init()
    fps = 30
    fpsClock = pygame.time.Clock()

    while c.events:
        c.tick(fpsClock.tick(fps))


You need to have a function that will shoot, hit, wait, allow for another shoot, then repeat.

2014-12-31 21:47:56 (edited by camlorn 2014-12-31 21:48:53)

Um.  He's in BGT, and I doubt he's quite ready for that.  I think he just wants to know how timers work, or something along those lines.
Anyhow, you might want to look at Twisted very closely.  I have recently discovered that, with a  bit of glue code to get it working with Pygame/etc, it makes a better event scheduler than anything we can homebrew.  You seem to be at the point where it wouldn't fry your brain, so you might want to look at some basic tutorials.  Twisted was originally for a game, even if everyone focuses on network programming.  Games wouldn't be using the deferred nearly as much, but it does provide everything you need and the concepts you learn also apply to database and network access, among other things.
That said, the game I'm doing using it is not yet released, etc, etc, etc.  But I've been getting huge mileage out of Twisted and something called the entity component system pattern.  Among other things, this has coincidentally provided an easy way to automatically serialize the world, separated my code out into different files like you wouldn't believe, provided a method whereby i can effectively ship the entire game state across the internet while it is running, and can do really crazy stuff without it crashing (you're a player. You're also a door).  Most of this was just an accident of the design, which is why I'm so impressed.  Also, a lot of the complexity for this type of thing-at least for a first person shooter-goes away if you actually make projectile objects when the gun fires and let the physics engine simulate them.  This provides a degree of separation between "the gun is firing" and "x is damaged", and lets the "x is damaged" code also apply to other stuff like environmental obstacles.
If you do go down this road, the magical piece you're looking for is called @inlineCallbacks.  I can't explain this without explaining Twisted, but when you get to the point wherein you're thinking about how you're going to need 20 functions to do everything it's time to Google this instead of giving up.  @inlineCallbacks was the piece I was missing when I first looked at twisted and, consequently, was directly responsible for me not learning it sooner.

My Blog
Twitter: @ajhicks1992

2014-12-31 22:26:36

I think he wants a way to shoot a machinegun.
This is... hmm... complicated. It can be more or less complicated, depending on the degree of realism. Tracking individual bullets would probably be a bit much, but doing it all at once might be a bit too simple.

This brings me back to my friend the Finite State Machine, or at least my (possibly broken) implementation. In your previous thread, It was extremely tempting to redo your whole enemy class as a Finite State Machine.
I'm not sure doing it that way would be good for teaching, though. :-/

看過來!
"If you want utopia but reality gives you Lovecraft, you don't give up, you carve your utopia out of the corpses of dead gods."
MaxAngor wrote:
    George... Don't do that.

2014-12-31 23:16:12

In BGt, yeah.  In Python, well, I'm writing the velocity loop no matter what, and Ode is right there ready to handle my collision, and if I do it the way you're suggesting then I end up actually writing more code by far.  All I need is a countdown to when the next bullet can fire (usually a time in seconds) and a countdown on the bullet object to when it destroys itself (velocities are fixed, so the calculation is straightforward; any system with an accurate timer can handle the death for me).  The code to actually do everything collides with everything has zero special cases in it.

My Blog
Twitter: @ajhicks1992

2015-01-01 00:52:15

A countdown to when the next bullet can fire is pretty much the major thing I was going for.
In this case, I think he wants to shoot off a burst of ~10 bullets, either all at once or rapidly.
Hence, state changes: start shooting plays the sound, fires the first bullet, possibly sets how many bullets remain. Call the update method continuously anyway, and the update method will fire the next bullet as needed, or set us to the cooldown state if done (and the "ready to shoot again" state after cooldown). It can be simplified so one doesn't need special states for everything, but that's pretty much where I was going with that.

看過來!
"If you want utopia but reality gives you Lovecraft, you don't give up, you carve your utopia out of the corpses of dead gods."
MaxAngor wrote:
    George... Don't do that.

2015-01-01 00:57:40

I'm just incredibly against state machines.  They have their purposes, but for games they seem to just be really prone to combinatorial explosion.  There are better things, just new programmers aren't ready for them.

My Blog
Twitter: @ajhicks1992

2015-01-01 01:23:17

I'll grant you that. My usual solution (which does not work here) is an object representing what states can do--geometric changes, attack details, changes in velocity, etc--and once the basic rules are coded, the majority of the work becomes making new states and adding them to a dict/HashMap/whatever the language in question calls it.
Discovering this was a pretty big breakthrough in my game development attempts. Then I started pulling back and if-elsing everything because I keep getting stuck after writing the skeletal class structure because my brain apparently really hates recreating physics. (*Opens a new tab to try and study ODE again*)

看過來!
"If you want utopia but reality gives you Lovecraft, you don't give up, you carve your utopia out of the corpses of dead gods."
MaxAngor wrote:
    George... Don't do that.

2015-01-01 01:49:16

Hello everyone!
;I have an enemy
;his weapon rifle
;in one shot, he spends all supplies
;how to do it on a timer in bgt?

2015-01-11 00:04:27

Well, that's all the code, here's how to put the shot delay is shot like 500 miles seconds:
#include "dynamic_menu.bgt"
#include "sound_pool.bgt"

const int board = 50;
int player_position = 0;
int player_hp = 500;
sound_pool pool;
sound_pool wep;
sound start;
sound music1;
sound music;
sound shag;

void main()
{
music.load("sounds/music.wav");
music.volume = -30;
music1.load("sounds/music1.wav");
music1.volume = -10;
shag.load("sounds/shag.wav");
shag.volume = 50;
start.load("sounds/start.wav");
start.volume = 30;
tts_voice voice;
dynamic_menu menu;
menu.allow_escape = true;
menu.wrap = true;
menu.add_item_tts("Start game");
menu.add_item_tts("Exit game");
show_game_window("Enemy");
voice.speak_wait("Welcome to Enemy");
music.play_looped();
int choice;
do
{
choice = menu.run("Please choose a menu item with the arrow keys, then hit enter to activate it.", true);
if(choice==1)
{
music.stop();
game_play();
}
}
while(choice!=0 and choice!=3);
music.stop();
voice.speak_wait("Thanks for playing.");
}

class enemy
{
int hp;
int position;
timer time;
int speed;
int ammo = 1000;
enemy()
{
hp = 10;
position = 50;
speed = 300;
}
void move() {
if(time.elapsed>=speed) {
if(position>player_position) position--;
else position++;
pool.play_1d("sounds/step.wav", player_position, position, false);
time.restart();
time.resume();
}
if(absolute(player_position-this.position)<=4 and this.ammo>0) {
wep.play_1d("sounds/vin.wav", player_position, position, false);
this.ammo--;
player_hp-10;
}
}
}

void game_play()
{
start.play();
while(start.playing)
{
if(key_pressed(KEY_RETURN))
{
start.stop();
break;
}
}
enemy enem;
while(true)
{
music1.play_looped();
if(key_pressed(KEY_F4))
{
exit();
}
if(key_pressed(KEY_LEFT) and player_position>0) {
player_position--;
shag.play();
}
if(key_pressed(KEY_RIGHT) and player_position<board) {
player_position++;
shag.play();
}
if(player_position<0)
{
player_position++;
}
if(player_position>board)
{
player_position--;
}
if(player_hp<=0)
{
exit();
}
enem.move();
}
}