duanleiming2014 2013-01-30 12:50
浏览 23
已采纳

在PHP游戏中每分钟更新数据库

I recently started programming in PHP. For exercise I'd like to build my own PHP text strategy game. One technical aspect needs some thinking.

In my game every player must have the ability to gain resources, for example iron and grain. With these resources a player is able to recruit soldiers or build buildings. The resources are stored in a kind of warehouse.

The resources will be gain in a period of time. In example you gain 100 grain a hour and that grain is stored in the warehouse. This means that every 0.6 minute, 1 grain has to be added. I have been looking to cron jobs but that is not the best answer to my problem because is takes too much system resource. The problem is that I'd like to be able to update my resources in my warehouse every minute. Does anyone have an idea for my problem?

  • 写回答

4条回答 默认 最新

  • dongshuofu0039 2013-01-30 13:18
    关注

    Rather than trying to solve this by updating state, you could look at trying to solve it in a functional programming way. E.g. write a function that can calculate the amount of resources, given known conditions (Such as when production was started). Very simplified:

    state based model:

    class Gold {
      public $amount = 0;
    }
    
    class GoldDigger {
      public $amount_per_second = 1;
    }
    
    $player_gold = new Gold();
    $player_worker = new GoldDigger();
    while (true) {
      $player_gold->amount += $player_worker->amount_per_second;
      sleep(1);
      echo "Player has {$player_gold->amount} gold pieces
    ";
    }
    

    functional based model:

    class Gold {
      public $workers = array();
      function getAmount() {
        $total = 0;
        foreach ($this->workers as $worker) {
          $total += $worker->getAmount();
        }
        return $total;
      }
    }
    
    class GoldDigger {
      public $amount_per_second = 1;
      public $started = 0;
      function __construct() {
        $this->started = time();
      }
      function getAmount() {
        return $this->amount_per_second * (time() - $this->started);
      }
    }
    
    $player_gold = new Gold();
    $player_gold->workers[] = new GoldDigger();
    
    while (true) {
      sleep(1);
      echo "Player has {$player_gold->getAmount()} gold pieces
    ";
    }
    

    Both these examples are a bit contrived - you would likely store the data in a database or similar, which complicates matters a bit, but I hope it illustrates the difference between the two strategies.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题