func main() { if err := sdl.Init(sdl.INIT_AUDIO); err != nil { log.Println(err) return } if err := mix.Init(mix.INIT_MP3); err != nil { log.Println(err) return } defer sdl.Quit() defer mix.Quit() defer mix.CloseAudio() if err := mix.OpenAudio(22050, mix.DEFAULT_FORMAT, 2, 4096); err != nil { log.Println(err) return } if music, err := mix.LoadMUS("test.mp3"); err != nil { log.Println(err) } else if err = music.Play(1); err != nil { log.Println(err) } else { sdl.Delay(5000) music.Free() } }
// DelayToNextFrame waits until it's time to do the next event/render loop func (g *GameManager) DelayToNextFrame() { curTime := sdl.GetTicks() if g.prevFrameTime == 0 { if curTime >= g.FrameDelay { g.prevFrameTime = curTime - g.FrameDelay } } diff := curTime - g.prevFrameTime if g.FrameDelay > diff { frameDelayUnder := g.FrameDelay - diff // we have not yet exceeded one frame, so we need to sleep //fmt.Printf("Under: %d %d %d %d\n", curTime, g.prevFrameTime, diff, frameDelayUnder) sdl.Delay(frameDelayUnder) } else { //frameDelayOver := diff - g.FrameDelay //fmt.Printf("Over: %d %d %d %d\n", curTime, g.prevFrameTime, diff, frameDelayOver) // we have exceeded one frame, so no sleep // TODO sleep less in the future to make up for it? } g.prevFrameTime = curTime }
func StateMachine(coreFunction Update, updateFunctionsToStartWith []Update) { UpdateFunctions = updateFunctionsToStartWith functionCount := len(updateFunctionsToStartWith) states := make([]int, functionCount) for i := 0; i < functionCount; i++ { states[i] = 0 } coreState := coreFunction(0) for coreState != -1 && functionCount != 0 { for i := 0; i < functionCount; i++ { states[i] = UpdateFunctions[i](states[i]) } newCount := len(UpdateFunctions) states = append(states, make([]int, newCount-functionCount)...) for i := functionCount; i < newCount; i++ { states[i] = 0 } for i := functionCount - 1; i >= 0; i-- { if states[i] == -1 { UpdateFunctions = append(UpdateFunctions[:i], UpdateFunctions[i+1:]...) states = append(states[:i], states[i+1:]...) } } functionCount = len(UpdateFunctions) sdl.Delay(15) coreState = coreFunction(coreState) } }
// Render updates the screen, based on the new positions of the bats and the ball. func render() { var fps uint32 fps = 60 var delay uint32 delay = 1000 / fps var frameStart uint32 frameStart = sdl.GetTicks() renderer.Clear() renderMyBat() renderComputersBat() renderScore() // if the game is over render the gameOver graphic if gameOver == true { renderGameOver() } else { // otherwise we need to draw the ball renderBall() } // Show the game window window. renderer.Present() var frameTime uint32 frameTime = sdl.GetTicks() - frameStart if frameTime < delay { sdl.Delay(delay - frameTime) } }
// Update is func (T *TextWidget) Update() { w := T.Geometry.Width // h := T.Geometry.Height var r sdl.Rect T.Clear() for i, line := range T.Content { r = sdl.Rect{ X: T.Padding.Left, Y: T.Padding.Top + int32(i*T.LineHeight), W: int32(w), H: int32(T.LineHeight), } T.DrawColoredText(line.Content, &r, "foreground", "default", line.Rules, ) } T.App.DrawMode() T.drawCursor() // T.Renderer.Clear() // T.Renderer.Present() sdl.Delay(5) T.App.Window.UpdateSurface() }
func main() { rom, err := LoadROM(os.Args[1]) if err != nil { panic(err) } frameDelay := 1000 / frameRate window := sdl.CreateWindow( "Go NES", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 256, 240, sdl.WINDOW_SHOWN, ) if window == nil { panic(sdl.GetError()) } defer window.Destroy() controller := NewController() ppu := NewPPU(window, NewVRAM(rom.Mapper())) cpu := NewCPU(NewMMU(rom.Mapper(), ppu, controller), ppu) ticksPerFrame := uint32(341 * 262) for { expectedTicks := sdl.GetTicks() + frameDelay for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() { switch event := event.(type) { case *sdl.KeyDownEvent: controller.SetKeyState(event.Keysym.Sym, true) case *sdl.KeyUpEvent: controller.SetKeyState(event.Keysym.Sym, false) case *sdl.QuitEvent: return } } ppuTicks := uint32(0) for ppuTicks < ticksPerFrame { ppuTicks += ppu.Tick(cpu.Tick()) } actualTicks := sdl.GetTicks() if actualTicks < expectedTicks { sdl.Delay(expectedTicks - actualTicks) } } }
func main() { var window *sdl.Window var renderer *sdl.Renderer var event sdl.Event var running bool window = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winWidth, winHeight, sdl.WINDOW_SHOWN) if window == nil { fmt.Fprintf(os.Stderr, "Failed to create window: %s\n", sdl.GetError()) os.Exit(1) } renderer = sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED) if renderer == nil { fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", sdl.GetError()) os.Exit(2) } var peepArray []sdl.Event = make([]sdl.Event, 5) running = true for running { sdl.PumpEvents() numEventsRetrieved := sdl.PeepEvents(peepArray, sdl.PEEKEVENT, sdl.FIRSTEVENT, sdl.LASTEVENT) if numEventsRetrieved < 0 { fmt.Printf("PeepEvents error: %s\n", sdl.GetError()) } else { for i := 0; i < numEventsRetrieved; i++ { fmt.Printf("Event Peeked Value: %v\n", peepArray[i]) // primitive printing of event } } for event = sdl.PollEvent(); event != nil; event = sdl.PollEvent() { switch t := event.(type) { case *sdl.QuitEvent: running = false case *sdl.MouseMotionEvent: fmt.Printf("[%d ms] MouseMotion\ttype:%d\tid:%d\tx:%d\ty:%d\txrel:%d\tyrel:%d\n", t.Timestamp, t.Type, t.Which, t.X, t.Y, t.XRel, t.YRel) case *sdl.MouseButtonEvent: fmt.Printf("[%d ms] MouseButton\ttype:%d\tid:%d\tx:%d\ty:%d\tbutton:%d\tstate:%d\n", t.Timestamp, t.Type, t.Which, t.X, t.Y, t.Button, t.State) case *sdl.MouseWheelEvent: fmt.Printf("[%d ms] MouseWheel\ttype:%d\tid:%d\tx:%d\ty:%d\n", t.Timestamp, t.Type, t.Which, t.X, t.Y) case *sdl.KeyUpEvent: fmt.Printf("[%d ms] Keyboard\ttype:%d\tsym:%c\tmodifiers:%d\tstate:%d\trepeat:%d\n", t.Timestamp, t.Type, t.Keysym.Sym, t.Keysym.Mod, t.State, t.Repeat) } } sdl.Delay(1000 / 30) } renderer.Destroy() window.Destroy() }
func run() int { var window *sdl.Window var renderer *sdl.Renderer var points []sdl.Point var rect sdl.Rect var rects []sdl.Rect window, err := sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winWidth, winHeight, sdl.WINDOW_SHOWN) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create window: %s\n", err) return 1 } defer window.Destroy() renderer, err = sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", err) return 2 } defer renderer.Destroy() renderer.Clear() renderer.SetDrawColor(255, 255, 255, 255) renderer.DrawPoint(150, 300) renderer.SetDrawColor(0, 0, 255, 255) renderer.DrawLine(0, 0, 200, 200) points = []sdl.Point{{0, 0}, {100, 300}, {100, 300}, {200, 0}} renderer.SetDrawColor(255, 255, 0, 255) renderer.DrawLines(points) rect = sdl.Rect{300, 0, 200, 200} renderer.SetDrawColor(255, 0, 0, 255) renderer.DrawRect(&rect) rects = []sdl.Rect{{400, 400, 100, 100}, {550, 350, 200, 200}} renderer.SetDrawColor(0, 255, 255, 255) renderer.DrawRects(rects) rect = sdl.Rect{250, 250, 200, 200} renderer.SetDrawColor(0, 255, 0, 255) renderer.FillRect(&rect) rects = []sdl.Rect{{500, 300, 100, 100}, {200, 300, 200, 200}} renderer.SetDrawColor(255, 0, 255, 255) renderer.FillRects(rects) renderer.Present() sdl.Delay(2000) return 0 }
func doesMyCodeWork2() { startTime := time.Now() for i := 0; i != -1; i++ { fmt.Print(i) fmt.Print(": ") timeDiff := time.Now().Second() + 60*time.Now().Minute() - startTime.Second() - startTime.Minute()*60 fmt.Println(timeDiff) sdl.Delay(1000) } }
func (g *Game) tick() { //var ticks uint32 g.defaultSleep = 300 // this param will control the speed somehow TODO Fix this sdl.Delay(1) if sdl.GetTicks()%g.defaultSleep == 0 { g.heartbeat(sdl.GetTicks()) } }
func main() { for game.loop { get_event() logic() renderer.Clear() render() renderer.Present() sdl.Delay(delay) } }
// Pause pauses execution of the game for the specified number of ticks. // During the pause period nothing will happen. All input will be ignored // and the window will not redraw. // // The duration of the pause must be specified in ticks in a variable // of type int64 // // Pause will panic if: // // 1. The toolbox has not been initialised. // // 2. The numnber of ticks is negative. func Pause(numberOfTicks int64) { if !initialised { // this stops execution here, so ne need for an else after the if panic(notInitialisedMessage) } if numberOfTicks < 0 { panic("Cannot pause. The numberOfTicks is negative.") } sdl.Delay(uint32(numberOfTicks)) }
//DispatchKeys interface method func (sw *Switcher) DispatchKeys(t *sdl.KeyDownEvent) int { app := sw.App T := app.Widget key := sdl.GetScancodeName(t.Keysym.Scancode) if (key == "N" && t.Keysym.Mod == 64) || key == "Down" { T.SetLine(sw.Selected, sw.getLine(sw.Selected, sw.Clients[sw.Selected], false)) if sw.Selected < len(sw.Clients)-1 { sw.Selected++ } else { sw.Selected = 0 } T.SetLine(sw.Selected, sw.getLine(sw.Selected, sw.Clients[sw.Selected], true)) return 1 } if (key == "P" && t.Keysym.Mod == 64) || key == "Up" { T.SetLine(sw.Selected, sw.getLine(sw.Selected, sw.Clients[sw.Selected], false)) if sw.Selected > 0 { sw.Selected-- } else { sw.Selected = len(sw.Clients) - 1 } T.SetLine(sw.Selected, sw.getLine(sw.Selected, sw.Clients[sw.Selected], true)) return 1 } if key == "X" && t.Keysym.Mod == 64 { wid := sw.Clients[sw.Selected].WID ewmh.CloseWindow(X, wid) sdl.Delay(500) sw.Clients = GetClients() sw.Draw() return 1 } if (key == "J" && t.Keysym.Mod == 64) || key == "Return" { wid := sw.Clients[sw.Selected].WID ewmh.ActiveWindowReq(X, wid) return 0 } if strings.Index("0123456789", key) > -1 { i, err := strconv.Atoi(key) if err == nil && len(sw.Clients) > i { sw.Selected = i if t.Keysym.Mod == 64 { wid := sw.Clients[sw.Selected].WID ewmh.ActiveWindowReq(X, wid) return 0 } sw.Draw() return 1 } } if t.Keysym.Sym == sdl.K_ESCAPE || t.Keysym.Sym == sdl.K_CAPSLOCK { return 0 } return 1 }
func main() { var window *sdl.Window var renderer *sdl.Renderer var points []sdl.Point var rect sdl.Rect var rects []sdl.Rect window = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winWidth, winHeight, sdl.WINDOW_SHOWN) if window == nil { fmt.Fprintf(os.Stderr, "Failed to create window: %s\n", sdl.GetError()) os.Exit(1) } renderer = sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED) if renderer == nil { fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", sdl.GetError()) os.Exit(2) } renderer.SetDrawColor(255, 255, 255, 255) renderer.DrawPoint(150, 300) renderer.SetDrawColor(0, 0, 255, 255) renderer.DrawLine(0, 0, 200, 200) points = []sdl.Point{{0, 0}, {100, 300}, {100, 300}, {200, 0}} renderer.SetDrawColor(255, 255, 0, 255) renderer.DrawLines(points) rect = sdl.Rect{300, 0, 200, 200} renderer.SetDrawColor(255, 0, 0, 255) renderer.DrawRect(&rect) rects = []sdl.Rect{{400, 400, 100, 100}, {550, 350, 200, 200}} renderer.SetDrawColor(0, 255, 255, 255) renderer.DrawRects(rects) rect = sdl.Rect{250, 250, 200, 200} renderer.SetDrawColor(0, 255, 0, 255) renderer.FillRect(&rect) rects = []sdl.Rect{{500, 300, 100, 100}, {200, 300, 200, 200}} renderer.SetDrawColor(255, 0, 255, 255) renderer.FillRects(rects) renderer.Present() sdl.Delay(2000) renderer.Destroy() window.Destroy() }
func main() { js, err := GetJs() if err != nil { panic(err) } for { axes := GetAxes(js) sdl.Delay(100) log.Println(axes) } }
func run() int { var window *sdl.Window var renderer *sdl.Renderer var texture *sdl.Texture var src, dst sdl.Rect var err error window, err = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winWidth, winHeight, sdl.WINDOW_SHOWN) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create window: %s\n", err) return 1 } defer window.Destroy() renderer, err = sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", err) return 2 } defer renderer.Destroy() image, err := img.Load(imageName) if err != nil { fmt.Fprintf(os.Stderr, "Failed to load PNG: %s\n", err) return 3 } defer image.Free() texture, err = renderer.CreateTextureFromSurface(image) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create texture: %s\n", err) return 4 } defer texture.Destroy() src = sdl.Rect{0, 0, 512, 512} dst = sdl.Rect{100, 50, 512, 512} renderer.Clear() renderer.SetDrawColor(255, 0, 0, 255) renderer.FillRect(&sdl.Rect{0, 0, int32(winWidth), int32(winHeight)}) renderer.Copy(texture, &src, &dst) renderer.Present() sdl.Delay(2000) return 0 }
func run() int { var window *sdl.Window var font *ttf.Font var surface *sdl.Surface var solid *sdl.Surface var err error sdl.Init(sdl.INIT_VIDEO) if err := ttf.Init(); err != nil { fmt.Fprintf(os.Stderr, "Failed to initialize TTF: %s\n", err) return 1 } if window, err = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winWidth, winHeight, sdl.WINDOW_SHOWN); err != nil { fmt.Fprintf(os.Stderr, "Failed to create window: %s\n", err) return 2 } defer window.Destroy() if font, err = ttf.OpenFont("../../assets/test.ttf", 32); err != nil { fmt.Fprint(os.Stderr, "Failed to open font: %s\n", err) return 4 } defer font.Close() if solid, err = font.RenderUTF8_Solid("Hello, World!", sdl.Color{255, 0, 0, 255}); err != nil { fmt.Fprint(os.Stderr, "Failed to render text: %s\n", err) return 5 } defer solid.Free() if surface, err = window.GetSurface(); err != nil { fmt.Fprint(os.Stderr, "Failed to get window surface: %s\n", err) return 6 } if err = solid.Blit(nil, surface, nil); err != nil { fmt.Fprint(os.Stderr, "Failed to put text on window surface: %s\n", err) return 7 } // Show the pixels for a while window.UpdateSurface() sdl.Delay(3000) return 0 }
func main() { music := openal.NewSource() music.SetLooping(false) if game.music { go play_music(music) musicThread = true } for game.loop { get_event() logic(music) renderer.Clear() render() renderer.Present() sdl.Delay(delay) } }
func main() { if len(os.Args) < 2 { fmt.Println("usage: emuChip8 <game>") os.Exit(1) } sdl.Init(sdl.INIT_EVERYTHING) window, err := sdl.CreateWindow("Chip8", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, WIN_WIDTH, WIN_HEIGHT, sdl.WINDOW_SHOWN) if err != nil { panic(err) } defer window.Destroy() surface, err := window.GetSurface() if err != nil { panic(err) } chip := new(Chip8) chip.surface = surface chip.init() chip.loadGame(os.Args[1]) chip.quit = false for !chip.quit { if err := chip.emulateCycle(); err != nil { fmt.Println(err) } if chip.drawFlag { chip.drawGraphics() window.UpdateSurface() chip.drawFlag = false } chip.setKeys() sdl.Delay(1) } chip.cleanup() }
func main() { var window *sdl.Window var renderer *sdl.Renderer var texture *sdl.Texture var src, dst sdl.Rect window = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winWidth, winHeight, sdl.WINDOW_SHOWN) if window == nil { fmt.Fprintf(os.Stderr, "Failed to create window: %s\n", sdl.GetError()) os.Exit(1) } renderer = sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED) if renderer == nil { fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", sdl.GetError()) os.Exit(2) } image := img.Load(imageName) if image == nil { fmt.Fprintf(os.Stderr, "Failed to load PNG: %s\n", sdl.GetError()) os.Exit(3) } texture = renderer.CreateTextureFromSurface(image) if texture == nil { fmt.Fprintf(os.Stderr, "Failed to create texture: %s\n", sdl.GetError()) os.Exit(4) } src = sdl.Rect{0, 0, 512, 512} dst = sdl.Rect{100, 50, 512, 512} renderer.Clear() renderer.SetDrawColor(255, 0, 0, 255) renderer.FillRect(&sdl.Rect{0, 0, int32(winWidth), int32(winHeight)}) renderer.Copy(texture, &src, &dst) renderer.Present() sdl.Delay(2000) image.Free() texture.Destroy() renderer.Destroy() window.Destroy() }
func main() { var window *sdl.Window var renderer *sdl.Renderer var image *sdl.Surface var texture *sdl.Texture var src, dst sdl.Rect var err error window, err = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winWidth, winHeight, sdl.WINDOW_SHOWN) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create window: %s\n", err) os.Exit(1) } defer window.Destroy() renderer, err = sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", err) os.Exit(2) } defer renderer.Destroy() image, err = sdl.LoadBMP(imageName) if err != nil { fmt.Fprintf(os.Stderr, "Failed to load BMP: %s\n", err) os.Exit(3) } defer image.Free() texture, err = renderer.CreateTextureFromSurface(image) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create texture: %s\n", err) os.Exit(4) } defer texture.Destroy() src = sdl.Rect{0, 0, 512, 512} dst = sdl.Rect{100, 50, 512, 512} renderer.Clear() renderer.Copy(texture, &src, &dst) renderer.Present() sdl.Delay(2000) }
func main() { // Run the game on main thread only. // This is important because SDL will freeze / crash // if an action is running outside the main thread runtime.LockOSThread() // Show us a welomce message log.Println("Welcome to Kaori") // Don't forget to say goodbye ;) defer log.Println("Goodbye o/") // Show information about the runtime log.Printf("Compiled with %s for %s %s\n", runtime.Compiler, runtime.GOOS, runtime.GOARCH) // Don't forget to clean the game after it's done game.Init("Kaori", sdl.WINDOWPOS_CENTERED, sdl.WINDOWPOS_CENTERED, 800, 600, false) // Don't forget to clean the game after it's done defer game.Clean() for game.Running() { // Get the current time to mark a frame start frameStart = sdl.GetTicks() // Run all of the 'update' functions game.HandleEvents() game.Update() game.Render() // Record the time frameTime = sdl.GetTicks() - frameStart // Check if it's faster than delay time if frameTime < DELAY_TIME { // If it is faster, delay the game to prevent "speeding" on certain tick event sdl.Delay(DELAY_TIME - frameTime) } } }
func pollJoystick(c chan [5]int16, m chan *godrone.MotorPWM) { js, err := joystick.GetJs() if err != nil { panic(err) } var trim float64 = 0.1 for { axes := joystick.GetAxes(js) sdl.Delay(100) c <- axes if axes[TRIM_AXIS] != 0 { var oper int64 = int64(axes[TRIM_AXIS]) - 128 delta := (float64(oper) / 65536) / TRIM_CHANGE trim += delta } if trim < 0 { trim = 0.0 } if trim > godrone.MAX_MOTOR { trim = godrone.MAX_MOTOR } var throttle float64 = 0.0 if axes[THROTTLE_AXIS] != 0 { var oper int64 = 32768 - int64(axes[THROTTLE_AXIS]) throttle = (float64(oper) / 65536) * trim } motors := godrone.MotorPWM{throttle} m <- &motors printRow(1, fmt.Sprintf("THrottle: %f ", throttle)) printRow(2, fmt.Sprintf("Trim: %f ", trim)) } }
func main() { sdl.Init(sdl.INIT_EVERYTHING) window, err := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 800, 600, sdl.WINDOW_SHOWN) if err != nil { panic(err) } defer window.Destroy() surface, err := window.GetSurface() if err != nil { panic(err) } rect := sdl.Rect{0, 0, 200, 200} surface.FillRect(&rect, 0xffff0000) window.UpdateSurface() sdl.Delay(1000) sdl.Quit() }
func main() { var window *sdl.Window var renderer *sdl.Renderer sdl.Init(sdl.INIT_EVERYTHING) window = createWindow(winTitle, winHeight, winWidth) defer window.Destroy() renderer = createRenderer(window) defer renderer.Destroy() var secTickChan = time.Tick(time.Second) var events = &Events{} var fps = 0 var view = NewGameView() for { // Pump events events.GetEvents() // Pass events and renderer to view view.Render(renderer, events) // This structure logs the fps select { case <-secTickChan: log.Println("fps:", fps) fps = 0 default: fps++ } // Delay the next frame rendering to free up CPU sdl.Delay(13) } }
func main() { sdl.Init(sdl.INIT_VIDEO) defer sdl.Quit() window, err := sdl.CreateWindow("Tank", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, windowWidth, windowHeight, 0) if err != nil { panic(err) } defer window.Destroy() mainloop: for { for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() { switch event.(type) { case *sdl.QuitEvent: break mainloop } } windowSurface, _ := window.GetSurface() windowSurface.FillRect(nil, sdl.MapRGB(windowSurface.Format, 0, 0, 0)) window.UpdateSurface() sdl.Delay(1000) } }
func main() { defaultConfig := config{ Axes: map[string][3]int{ strconv.Itoa(sdl.CONTROLLER_AXIS_LEFTX): {0x4000, 0x7B, 0x7C}, // Arrow Left + Right strconv.Itoa(sdl.CONTROLLER_AXIS_LEFTY): {0x4000, 0x7E, 0x7D}, // Arrow Up + Down strconv.Itoa(sdl.CONTROLLER_AXIS_RIGHTX): {0x4000, 0x00, 0x07}, // A + X strconv.Itoa(sdl.CONTROLLER_AXIS_RIGHTY): {0x4000, 0x01, 0x06}, // S + Z }, Buttons: map[string]int{ strconv.Itoa(sdl.CONTROLLER_BUTTON_DPAD_UP): 0X7E, // Up strconv.Itoa(sdl.CONTROLLER_BUTTON_DPAD_DOWN): 0X7D, // Down strconv.Itoa(sdl.CONTROLLER_BUTTON_DPAD_LEFT): 0x7B, // Left strconv.Itoa(sdl.CONTROLLER_BUTTON_DPAD_RIGHT): 0x7C, // Right strconv.Itoa(sdl.CONTROLLER_BUTTON_A): 0X06, // Z strconv.Itoa(sdl.CONTROLLER_BUTTON_B): 0x07, // X strconv.Itoa(sdl.CONTROLLER_BUTTON_X): 0x00, // A strconv.Itoa(sdl.CONTROLLER_BUTTON_Y): 0x01, // S strconv.Itoa(sdl.CONTROLLER_BUTTON_LEFTSHOULDER): 0x0C, // Q strconv.Itoa(sdl.CONTROLLER_BUTTON_RIGHTSHOULDER): 0x0D, // W strconv.Itoa(sdl.CONTROLLER_BUTTON_LEFTSTICK): 0x38, // Shift strconv.Itoa(sdl.CONTROLLER_BUTTON_RIGHTSTICK): 0x3B, // Ctrl strconv.Itoa(sdl.CONTROLLER_BUTTON_BACK): 0x33, // Delete strconv.Itoa(sdl.CONTROLLER_BUTTON_GUIDE): 0x30, // Tab strconv.Itoa(sdl.CONTROLLER_BUTTON_START): 0x24, // Return }, Triggers: map[string][2]int{ strconv.Itoa(sdl.CONTROLLER_AXIS_TRIGGERLEFT): {0x4000, 0x0E}, // E strconv.Itoa(sdl.CONTROLLER_AXIS_TRIGGERRIGHT): {0x4000, 0x0F}, // R }, } conf := newConfig() if file, err := os.Open("config.json"); err != nil { f, err := os.Create("config.json") if err != nil { log.Fatal(err) } defer f.Close() conf = defaultConfig buf, err := json.MarshalIndent(conf, "", " ") if err != nil { log.Fatal(err) } f.Write(buf) } else { err := json.NewDecoder(file).Decode(&conf) if err != nil { os.Remove("config.json") log.Fatal(err) } file.Close() } controller, err := newController(conf) if err != nil { log.Fatal(err) } defer controller.close() err = sdl.Init((1 << 14) | sdl.INIT_GAMECONTROLLER) if err != nil { log.Fatal(err) } defer sdl.Quit() sdlController := sdl.GameControllerOpen(0) if sdlController == nil { log.Fatal(sdl.GetError()) } defer sdlController.Close() for { for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() { switch e := e.(type) { case *sdl.ControllerButtonEvent: if e.State == 0 { controller.Buttons[int(e.Button)].handleUp() } else { controller.Buttons[int(e.Button)].handleDown() } case *sdl.ControllerAxisEvent: if e.Axis == sdl.CONTROLLER_AXIS_TRIGGERLEFT || e.Axis == sdl.CONTROLLER_AXIS_TRIGGERRIGHT { controller.Triggers[int(e.Axis)].handleEvent(int(e.Value)) } else { controller.Axes[int(e.Axis)].handleEvent(int(e.Value)) } } } sdl.Delay(10) } }
func main() { var window *sdl.Window var renderer *sdl.Renderer var event sdl.Event var running bool window = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, winWidth, winHeight, sdl.WINDOW_SHOWN) if window == nil { fmt.Fprintf(os.Stderr, "Failed to create window: %s\n", sdl.GetError()) os.Exit(1) } renderer = sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED) if renderer == nil { fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", sdl.GetError()) os.Exit(2) } var peepArray []sdl.Event = make([]sdl.Event, 2) peepArray[0] = &sdl.UserEvent{sdl.USEREVENT, sdl.GetTicks(), window.GetID(), 1331, nil, nil} peepArray[1] = &sdl.UserEvent{sdl.USEREVENT, sdl.GetTicks(), window.GetID(), 10101, nil, nil} running = true lastPushTime := sdl.GetTicks() for running { if lastPushTime+pushTime < sdl.GetTicks() { lastPushTime = sdl.GetTicks() sdl.PumpEvents() numEventsHandled := sdl.PeepEvents(peepArray, sdl.ADDEVENT, sdl.FIRSTEVENT, sdl.LASTEVENT) if numEventsHandled < 0 { fmt.Printf("PeepEvents error: %s\n", sdl.GetError()) } else { fmt.Printf("Successful push of %d events\n", numEventsHandled) } } for event = sdl.PollEvent(); event != nil; event = sdl.PollEvent() { switch t := event.(type) { case *sdl.QuitEvent: running = false case *sdl.MouseMotionEvent: fmt.Printf("[%d ms] MouseMotion\ttype:%d\tid:%d\tx:%d\ty:%d\txrel:%d\tyrel:%d\n", t.Timestamp, t.Type, t.Which, t.X, t.Y, t.XRel, t.YRel) case *sdl.MouseButtonEvent: fmt.Printf("[%d ms] MouseButton\ttype:%d\tid:%d\tx:%d\ty:%d\tbutton:%d\tstate:%d\n", t.Timestamp, t.Type, t.Which, t.X, t.Y, t.Button, t.State) case *sdl.MouseWheelEvent: fmt.Printf("[%d ms] MouseWheel\ttype:%d\tid:%d\tx:%d\ty:%d\n", t.Timestamp, t.Type, t.Which, t.X, t.Y) case *sdl.KeyUpEvent: fmt.Printf("[%d ms] Keyboard\ttype:%d\tsym:%c\tmodifiers:%d\tstate:%d\trepeat:%d\n", t.Timestamp, t.Type, t.Keysym.Sym, t.Keysym.Mod, t.State, t.Repeat) case *sdl.UserEvent: fmt.Printf("[%d ms] UserEvent\tcode:%d\n", t.Timestamp, t.Code) } } sdl.Delay(1000 / 30) } renderer.Destroy() window.Destroy() }
func (w Window) Refresh() { sdl.Delay(1) sdl.GL_SwapWindow(w.windowSDL) }
// Initialize func main() { var window *sdl.Window var renderer *sdl.Renderer var err error window, err = sdl.CreateWindow(winTitle, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, int(winWidth), int(winHeight), sdl.WINDOW_SHOWN) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create window: %s\n", err) os.Exit(1) } defer window.Destroy() renderer, err = sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", err) os.Exit(2) } defer renderer.Destroy() tilesetImg, err := img.Load("assets/textures/ts1.png") if err != nil { fmt.Fprintf(os.Stderr, "Failed to load PNG: %s\n", err) os.Exit(3) } defer tilesetImg.Free() tilesetTxt, err := renderer.CreateTextureFromSurface(tilesetImg) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create texture: %s\n", err) os.Exit(4) } defer tilesetTxt.Destroy() spritesheetImg, err := img.Load("assets/textures/actor3.png") if err != nil { fmt.Fprintf(os.Stderr, "Failed to load PNG: %s\n", err) os.Exit(3) } defer spritesheetImg.Free() spritesheetTxt, err := renderer.CreateTextureFromSurface(spritesheetImg) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create texture: %s\n", err) os.Exit(4) } defer spritesheetTxt.Destroy() err = ttf.Init() font, err = ttf.OpenFont("assets/textures/PressStart2P.ttf", 18) if err != nil { fmt.Fprintf(os.Stderr, "Failed to load font file: %s\n", err) os.Exit(6) } if err := sdl.Init(sdl.INIT_AUDIO); err != nil { fmt.Fprintf(os.Stderr, "Failed to load music file: %s\n", err) os.Exit(7) } if err := mix.Init(mix.INIT_MP3); err != nil { fmt.Fprintf(os.Stderr, "Failed to load music file: %s\n", err) os.Exit(8) } currScene = &eng.Scene{ Window: eng.Window{winWidth, winHeight}, StartTime: time.Now(), Cam: eng.Camera{0, 0}, EnemyCount: 99, TsTxt: tilesetTxt, SsTxt: spritesheetTxt, Font: font, } currScene.Init(renderer) var running bool = true for running { then := time.Now() running = catchEvents() //currScene.Update() currScene.Render(renderer) dur := time.Since(then) sdl.Delay(40 - uint32(dur.Nanoseconds()/1000000)) currScene.FrameCounter++ } }