Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. // go build benchmark.go && time ./benchmark
  2. package main
  3.  
  4. import (
  5. "fmt"
  6. "math/rand"
  7. )
  8.  
  9. type Player struct {
  10. hp int
  11. }
  12.  
  13. func NewPlayer() Player {
  14. return Player{hp: 100}
  15. }
  16.  
  17. type Cell struct {
  18. x int
  19. y int
  20. item *Player
  21. }
  22.  
  23. type World struct {
  24. width int
  25. height int
  26. grid [][]Cell
  27. }
  28.  
  29. func NewWorld(width, height int) World {
  30. fmt.Println("creating a grid with width=", width, " height=", height)
  31.  
  32. grid := make([][]Cell, height)
  33.  
  34. for y := 0; y < height; y++ {
  35. row := make([]Cell, width)
  36. for x := 0; x < width; x++ {
  37. row[x] = Cell{x, y, nil}
  38. }
  39. grid[y] = row
  40. }
  41.  
  42. return World{width, height, grid}
  43. }
  44.  
  45. func (world *World) CountPlayers() int {
  46. n := 0
  47. for _, row := range world.grid {
  48. for _, cell := range row {
  49. if cell.item != nil {
  50. n++
  51. }
  52. }
  53. }
  54. return n
  55. }
  56.  
  57. func (world *World) SpawnPlayers(count int) {
  58. fmt.Println("spawning ", count, " players")
  59.  
  60. for i := 0; i < count; i++ {
  61. x := rand.Intn(world.width)
  62. y := rand.Intn(world.height)
  63. player := NewPlayer()
  64. world.grid[y][x].item = &player
  65. }
  66. }
  67.  
  68. func main() {
  69. N := 10_000
  70. ROUNDS := 10
  71.  
  72. for i := 0; i < ROUNDS; i++ {
  73. fmt.Println("round ", i+1)
  74. world := NewWorld(N, N)
  75. world.SpawnPlayers(N * 100)
  76. fmt.Println(world.CountPlayers())
  77. }
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement