doumei7420 2012-12-08 09:03
浏览 27
已采纳

golang-网络游戏中的主循环

I've only begun tinkering with Go for about a week now, and am quite impressed with it. However, I'm still having a few issues I can't get my head around yet.

The main problem right now is that while I have the connection handling code working, I want to add a main game loop independent of the connection loop. How does one do this?

package main

import (
  "fmt"
  "net"
  "strconv"
  "time"
  "galaxy"
)

const PORT = 5555

func main() {
  playerFactory := galaxy.NewPlayerFactory()

  server, err := net.Listen("tcp", ":" + strconv.Itoa(PORT))
  if server == nil {
    panic("listen failed: " + err.Error() + "
")
  } else {
    defer server.Close()
  }

  // main loop  
  go func() {
    for {   
      // entity updates
      playerFactory.Update()
    }
  }() // adding this just blocks everything after the goroutine

  // connection handling
  for {
    conn, err := server.Accept()
    if err != nil {
      fmt.Printf("client error: %s
", err.Error())
    } else {
      playerFactory.CreatePlayer(conn)
    }
  }

}

With the way it is currently written the main loop runs (this is the part I am trying to add), but the connection handling code gets ignored. Is this where one uses channels to pass control around? I'm sure the solution is apparent to a more seasoned Go programmer, I look forward to your answers.

  • 写回答

1条回答 默认 最新

  • dtihe8614 2012-12-08 09:09
    关注

    If playerFactory.Update() never releases the CPU (for example by blocking on a resource), there is no guarantee for other goroutines to run

    You could try to change GOMAXPROCS but that would depend on your number of CPU and the problem would reappear later with other non blocking goroutines.

    And I can't see any reason for a game loop to run without interruption. The most frequent case is when you have to do something at regular interval.

    In this case, your code would be

      // main loop  
      go func() {
         timer := time.Tick(100 * time.Millisecond)
         for now := range timer {   
             // entity updates (you could use now for physic engine calculs)
             // this is called every 100 millisecondes
             playerFactory.Update()
         }
      }()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算