func main() {
	if sdl.Init(sdl.INIT_VIDEO) < 0 {
		panic("Video initialization failed: " + sdl.GetError())
	}

	if sdl.EnableKeyRepeat(100, 25) != 0 {
		panic("Setting keyboard repeat failed: " + sdl.GetError())
	}

	videoFlags := sdl.OPENGL    // Enable OpenGL in SDL
	videoFlags |= sdl.DOUBLEBUF // Enable double buffering
	videoFlags |= sdl.HWPALETTE // Store the palette in hardware
	// FIXME: this causes segfault.
	// videoFlags |= sdl.RESIZABLE // Enable window resizing

	surface = sdl.SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, uint32(videoFlags))

	if surface == nil {
		panic("Video mode set failed: " + sdl.GetError())
	}

	sdl.GL_SetAttribute(sdl.GL_DOUBLEBUFFER, 1)
	initGL()
	resizeWindow(SCREEN_WIDTH, SCREEN_HEIGHT)

	SetupWorld("data/world.txt")

	// wait for events
	running := true
	isActive := true
	for running {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.ActiveEvent:
				isActive = e.Gain != 0
			case *sdl.ResizeEvent:
				width, height := int(e.W), int(e.H)
				surface = sdl.SetVideoMode(width, height, SCREEN_BPP, uint32(videoFlags))
				if surface == nil {
					fmt.Println("Could not get a surface after resize:", sdl.GetError())
					Quit(1)
				}
				resizeWindow(width, height)
			case *sdl.KeyboardEvent:
				if e.Type == sdl.KEYDOWN {
					handleKeyPress(e.Keysym)
				}
			case *sdl.QuitEvent:
				running = false
			}
		}

		// draw the scene
		if isActive {
			drawGLScene(sector1)
		}
	}
}
예제 #2
0
func main() {

	sdl.Init(sdl.INIT_VIDEO)

	var screen = sdl.SetVideoMode(640, 480, 32, sdl.OPENGL)

	if screen == nil {
		panic("sdl error")
	}

	if gl.Init() != 0 {
		panic("gl error")
	}

	pen := Pen{}

	gl.MatrixMode(gl.PROJECTION)

	gl.Viewport(0, 0, int(screen.W), int(screen.H))
	gl.LoadIdentity()
	gl.Ortho(0, float64(screen.W), float64(screen.H), 0, -1.0, 1.0)

	gl.ClearColor(1, 1, 1, 0)
	gl.Clear(gl.COLOR_BUFFER_BIT)

	var running = true

	for running {

		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch ev := e.(type) {
			case *sdl.QuitEvent:
				running = false
			case *sdl.KeyboardEvent:
				if ev.Keysym.Sym == sdl.K_ESCAPE {
					running = false
				}
			case *sdl.MouseMotionEvent:
				if ev.State != 0 {
					pen.lineTo(Point{int(ev.X), int(ev.Y)})
				} else {
					pen.moveTo(Point{int(ev.X), int(ev.Y)})
				}
			}
		}

		sdl.GL_SwapBuffers()
		sdl.Delay(25)
	}

	sdl.Quit()

}
예제 #3
0
func main() {
	initialWidth, initialHeight := 1280, 720
	runtime.LockOSThread()
	if sdlInit := sdl.Init(sdl.INIT_VIDEO); sdlInit != 0 {
		panic("SDL init error")
	}
	reinitScreen(initialWidth, initialHeight)
	defer cleanExit(true, false)
	if err := gl.Init(); err != nil {
		panic(err)
	}
	gl.Enable(gl.BLEND)
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
	gl.Enable(gl.DEPTH)
	defer cleanExit(false, true)
	glSetupShaderProg(&shaderTextureCreator, false)
	glSetupShaderProg(&shaderTextureDisplay, true)
	glFillBuffer(rttVerts, &rttVertBuf)
	glFillBuffer(dispVerts, &dispVertBuf)
	gl.GenTextures(1, &rttFrameTex)
	gl.BindTexture(gl.TEXTURE_2D, rttFrameTex)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
	if doRtt {
		gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texSize, texSize, 0, gl.RGBA, gl.UNSIGNED_BYTE, nil)
		gl.GenFramebuffers(1, &rttFrameBuf)
		gl.BindFramebuffer(gl.FRAMEBUFFER, rttFrameBuf)
		gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, rttFrameTex, 0)
		gl.BindFramebuffer(gl.FRAMEBUFFER, 0)
	} else {
		glFillTextureFromImageFile("texture.jpg")
	}
	gl.BindTexture(gl.TEXTURE_2D, 0)
	gl.ClearColor(0.3, 0.6, 0.9, 1)
	gl.Clear(gl.COLOR_BUFFER_BIT)
	gl.ActiveTexture(gl.TEXTURE0)
	for {
		if evt := sdl.PollEvent(); evt != nil {
			switch event := evt.(type) {
			case *sdl.ResizeEvent:
				reinitScreen(int(event.W), int(event.H))
			case *sdl.QuitEvent:
				return
			}
		} else {
			if doRtt {
				renderToTexture()
			}
			renderToScreen()
			sdl.GL_SwapBuffers()
		}
	}

	sdl.Quit()
}
예제 #4
0
파일: gui.go 프로젝트: GunioRobot/Go-SDL
func (win *window) eventLoop() {
	if win.ec == nil {
		win.ec = make(chan interface{})
	}

eloop:
	for win.events {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.KeyboardEvent:
				switch e.Type {
				case sdl.KEYUP:
					win.ec <- gui.KeyEvent{int(-e.Keysym.Sym)}
				case sdl.KEYDOWN:
					win.ec <- gui.KeyEvent{int(e.Keysym.Sym)}
				}
			case *sdl.MouseMotionEvent:
				win.ec <- gui.MouseEvent{
					Buttons: int(e.State),
					Loc:     image.Pt(int(e.X), int(e.Y)),
					Nsec:    time.Nanoseconds(),
				}
			case *sdl.MouseButtonEvent:
				win.ec <- gui.MouseEvent{
					Buttons: int(sdl.GetMouseState(nil, nil)),
					Loc:     image.Pt(int(e.X), int(e.Y)),
					Nsec:    time.Nanoseconds(),
				}
			case *sdl.ResizeEvent:
				win.ec <- gui.ConfigEvent{image.Config{
					win.Screen().ColorModel(),
					int(e.W),
					int(e.H),
				}}
			case *sdl.QuitEvent:
				break eloop
			}
		}
	}

	close(win.ec)
}
예제 #5
0
파일: game.go 프로젝트: WaylandGod/Go2D
//Game loop
func (game *Game) Run() {
	defer game.Exit()

	if game.initFun == nil {
		fmt.Println("Go2D Warning: No init function set!")
	}

	if game.updateFun == nil {
		fmt.Println("Go2D Warning: No update function set!")
	}

	if game.drawFun == nil {
		fmt.Println("Go2D Warning: No draw function set!")
	}

	//Initialize the game
	game.initialize()

	var dt, old_t, now_t uint32 = 0, 0, 0

	for g_running {
		//Check for events and handle them
		for {
			event, present := sdl.PollEvent()
			if present {
				EventHandler(event)
			} else {
				break
			}
		}

		//Calculate time delta
		now_t = sdl.GetTicks()
		dt = now_t - old_t
		old_t = now_t

		//Update
		game.update(dt)

		//Draw
		game.draw()

		//Give the CPU some time to do other stuff
		sdl.Delay(1)
	}
}
예제 #6
0
파일: test.go 프로젝트: GunioRobot/Go-SDL
func main() {

	if sdl.Init(sdl.INIT_EVERYTHING) != 0 {
		panic(sdl.GetError())
	}

	if ttf.Init() != 0 {
		panic(sdl.GetError())
	}

	if mixer.OpenAudio(mixer.DEFAULT_FREQUENCY, mixer.DEFAULT_FORMAT,
		mixer.DEFAULT_CHANNELS, 4096) != 0 {
		panic(sdl.GetError())
	}

	var screen = sdl.SetVideoMode(640, 480, 32, sdl.RESIZABLE)

	if screen == nil {
		panic(sdl.GetError())
	}

	var video_info = sdl.GetVideoInfo()

	println("HW_available = ", video_info.HW_available)
	println("WM_available = ", video_info.WM_available)
	println("Video_mem = ", video_info.Video_mem, "kb")

	sdl.EnableUNICODE(1)

	sdl.WM_SetCaption("Go-SDL SDL Test", "")

	image := sdl.Load("test.png")

	if image == nil {
		panic(sdl.GetError())
	}

	sdl.WM_SetIcon(image, nil)

	running := true

	font := ttf.OpenFont("Fontin Sans.otf", 72)

	if font == nil {
		panic(sdl.GetError())
	}

	font.SetStyle(ttf.STYLE_UNDERLINE)
	white := sdl.Color{255, 255, 255, 0}
	text := ttf.RenderText_Blended(font, "Test (with music)", white)
	music := mixer.LoadMUS("test.ogg")
	sound := mixer.LoadWAV("sound.ogg")

	if music == nil || sound == nil {
		panic(sdl.GetError())
	}

	music.PlayMusic(-1)

	if sdl.GetKeyName(270) != "[+]" {
		panic("GetKeyName broken")
	}

	worm_in := make(chan Point)
	draw := make(chan Point, 64)

	var out chan Point
	var in chan Point

	out = worm_in

	in = out
	out = make(chan Point)
	go worm(in, out, draw)

	for running {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.QuitEvent:
				running = false
				break
			case *sdl.KeyboardEvent:
				println("")
				println(e.Keysym.Sym, ": ", sdl.GetKeyName(sdl.Key(e.Keysym.Sym)))

				if e.Keysym.Sym == 27 {
					running = false
				}

				fmt.Printf("%04x ", e.Type)

				for i := 0; i < len(e.Pad0); i++ {
					fmt.Printf("%02x ", e.Pad0[i])
				}
				println()

				fmt.Printf("Type: %02x Which: %02x State: %02x Pad: %02x\n", e.Type, e.Which, e.State, e.Pad0[0])
				fmt.Printf("Scancode: %02x Sym: %08x Mod: %04x Unicode: %04x\n", e.Keysym.Scancode, e.Keysym.Sym, e.Keysym.Mod, e.Keysym.Unicode)
			case *sdl.MouseButtonEvent:
				if e.Type == sdl.MOUSEBUTTONDOWN {
					println("Click:", e.X, e.Y)
					in = out
					out = make(chan Point)
					go worm(in, out, draw)
					sound.PlayChannel(-1, 0)
				}
			case *sdl.ResizeEvent:
				println("resize screen ", e.W, e.H)

				screen = sdl.SetVideoMode(int(e.W), int(e.H), 32, sdl.RESIZABLE)

				if screen == nil {
					panic(sdl.GetError())
				}
			}
		}

		screen.FillRect(nil, 0x302019)
		screen.Blit(&sdl.Rect{0, 0, 0, 0}, text, nil)

		loop := true

		for loop {

			select {
			case p := <-draw:
				screen.Blit(&sdl.Rect{int16(p.x), int16(p.y), 0, 0}, image, nil)
			case <-out:
			default:
				loop = false
			}

		}

		var p Point
		sdl.GetMouseState(&p.x, &p.y)
		worm_in <- p

		screen.Flip()
		sdl.Delay(25)
	}

	image.Free()
	music.Free()
	font.Close()

	ttf.Quit()
	sdl.Quit()
}
func main() {
	// Initialize SDL
	if sdl.Init(sdl.INIT_VIDEO) < 0 {
		panic("Video initialization failed: " + sdl.GetError())
	}

	// flags to pass to sdl.SetVideoMode
	videoFlags := sdl.OPENGL    // Enable OpenGL in SDL
	videoFlags |= sdl.DOUBLEBUF // Enable double buffering
	videoFlags |= sdl.HWPALETTE // Store the palette in hardware
	// FIXME: this causes segfault.
	// videoFlags |= sdl.RESIZABLE // Enable window resizing

	// get a SDL surface
	surface = sdl.SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, uint32(videoFlags))

	// verify there is a surface
	if surface == nil {
		panic("Video mode set failed: " + sdl.GetError())
		Quit(1)
	}

	// When this function is finished, clean up and exit.
	defer Quit(0)

	// Sets up OpenGL double buffering
	sdl.GL_SetAttribute(sdl.GL_DOUBLEBUFFER, 1)

	// Execute everything needed for OpenGL
	initGL()

	// Resize the initial window
	resizeWindow(SCREEN_WIDTH, SCREEN_HEIGHT)

	// wait for events
	running := true
	isActive := true
	for running {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.ActiveEvent:
				isActive = e.Gain != 0
			case *sdl.ResizeEvent:
				width, height := int(e.W), int(e.H)
				surface = sdl.SetVideoMode(width, height, SCREEN_BPP, uint32(videoFlags))

				if surface == nil {
					fmt.Println("Could not get a surface after resize:", sdl.GetError())
					Quit(1)
				}
				resizeWindow(width, height)
			case *sdl.KeyboardEvent:
				if e.Type == sdl.KEYDOWN {
					handleKeyPress(e.Keysym)
				}
			case *sdl.QuitEvent:
				running = false
			}
		}

		// draw the scene
		if isActive {
			drawGLScene()
		}
	}
}
예제 #8
0
파일: sdlgears.go 프로젝트: nkostelnik/gl
func main() {

	flag.Parse()

	var done bool
	var keys []uint8

	sdl.Init(sdl.INIT_VIDEO)

	var screen = sdl.SetVideoMode(300, 300, 16, sdl.OPENGL|sdl.RESIZABLE)

	if screen == nil {
		sdl.Quit()
		panic("Couldn't set 300x300 GL video mode: " + sdl.GetError() + "\n")
	}

	if gl.Init() != 0 {
		panic("gl error")
	}

	sdl.WM_SetCaption("Gears", "gears")

	init_()
	reshape(int(screen.W), int(screen.H))
	done = false
	for !done {

		idle()
		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch e.(type) {
			case *sdl.ResizeEvent:
				re := e.(*sdl.ResizeEvent)
				screen = sdl.SetVideoMode(int(re.W), int(re.H), 16,
					sdl.OPENGL|sdl.RESIZABLE)
				if screen != nil {
					reshape(int(screen.W), int(screen.H))
				} else {
					panic("we couldn't set the new video mode??")
				}
				break

			case *sdl.QuitEvent:
				done = true
				break
			}
		}
		keys = sdl.GetKeyState()

		if keys[sdl.K_ESCAPE] != 0 {
			done = true
		}
		if keys[sdl.K_UP] != 0 {
			view_rotx += 5.0
		}
		if keys[sdl.K_DOWN] != 0 {
			view_rotx -= 5.0
		}
		if keys[sdl.K_LEFT] != 0 {
			view_roty += 5.0
		}
		if keys[sdl.K_RIGHT] != 0 {
			view_roty -= 5.0
		}
		if keys[sdl.K_z] != 0 {
			if (sdl.GetModState() & sdl.KMOD_RSHIFT) != 0 {
				view_rotz -= 5.0
			} else {
				view_rotz += 5.0
			}
		}

		draw()
	}
	sdl.Quit()
	return

}
예제 #9
0
파일: gomandel.go 프로젝트: nkostelnik/gl
func main() {
	runtime.LockOSThread()
	flag.Parse()
	buildPalette()
	sdl.Init(sdl.INIT_VIDEO)
	defer sdl.Quit()

	sdl.GL_SetAttribute(sdl.GL_SWAP_CONTROL, 1)

	if sdl.SetVideoMode(512, 512, 32, sdl.OPENGL) == nil {
		panic("sdl error")
	}

	if gl.Init() != 0 {
		panic("gl error")
	}

	sdl.WM_SetCaption("Gomandel", "Gomandel")

	gl.Enable(gl.TEXTURE_2D)
	gl.Viewport(0, 0, 512, 512)
	gl.MatrixMode(gl.PROJECTION)
	gl.LoadIdentity()
	gl.Ortho(0, 512, 512, 0, -1, 1)

	gl.ClearColor(0, 0, 0, 0)

	//-----------------------------------------------------------------------------
	var dndDragging bool = false
	var dndStart Point
	var dndEnd Point
	var tex gl.Texture
	var tc TexCoords
	var lastProgress int
	initialRect := Rect{-1.5, -1.5, 3, 3}
	rect := initialRect

	rc := new(MandelbrotRequest)
	rc.MakeRequest(512, 512, rect)
	rc.WaitFor(Small, &tex, &tc)

	running := true
	for running {
		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch e.(type) {
			case *sdl.QuitEvent:
				running = false
			case *sdl.MouseButtonEvent:
				mbe := e.(*sdl.MouseButtonEvent)
				if mbe.Type == sdl.MOUSEBUTTONDOWN {
					dndDragging = true
					sdl.GetMouseState(&dndStart.X, &dndStart.Y)
					dndEnd = dndStart
				} else {
					dndDragging = false
					sdl.GetMouseState(&dndEnd.X, &dndEnd.Y)
					if mbe.Which == 3 {
						rect = initialRect
					} else {
						rect = rectFromSelection(dndStart, dndEnd, 512, 512, rect)
						tc = texCoordsFromSelection(dndStart, dndEnd, 512, 512, tc)
					}

					// make request
					rc.MakeRequest(512, 512, rect)
				}
			case *sdl.MouseMotionEvent:
				if dndDragging {
					sdl.GetMouseState(&dndEnd.X, &dndEnd.Y)
				}
			}
		}

		// if we're waiting for a result, check if it's ready
		p := rc.Update(&tex, &tc)
		if p != -1 {
			lastProgress = p
		}

		gl.Clear(gl.COLOR_BUFFER_BIT)
		tex.Bind(gl.TEXTURE_2D)
		drawQuad(0, 0, 512, 512, tc.TX, tc.TY, tc.TX2, tc.TY2)
		gl.BindTexture(gl.TEXTURE_2D, 0)
		if dndDragging {
			drawSelection(dndStart, dndEnd)
		}
		drawProgress(512, 512, lastProgress, rc.Pending)
		sdl.GL_SwapBuffers()
	}
}
예제 #10
0
파일: gotris.go 프로젝트: sonald/gotris
func main() {
	runtime.LockOSThread()
	flag.Parse()
	sdl.Init(sdl.INIT_VIDEO)
	defer sdl.Quit()

	sdl.GL_SetAttribute(sdl.GL_SWAP_CONTROL, 1)

	if sdl.SetVideoMode(640, 480, 32, sdl.OPENGL) == nil {
		panic("sdl error")
	}

	sdl.WM_SetCaption("Gotris", "Gotris")
	sdl.EnableKeyRepeat(250, 45)

	gl.Enable(gl.TEXTURE_2D)
	gl.Enable(gl.BLEND)
	gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
	gl.Viewport(0, 0, 640, 480)
	gl.MatrixMode(gl.PROJECTION)
	gl.LoadIdentity()
	gl.Ortho(0, 640, 480, 0, -1, 1)

	gl.ClearColor(0, 0, 0, 0)

	//-----------------------------------------------------------------------------

	font, err := LoadFontFromFile("dejavu.font")
	if err != nil {
		panic(err)
	}

	rand.Seed(int64(sdl.GetTicks()))

	gs := NewGameSession(*initLevel, font)
	lastTime := sdl.GetTicks()

	running := true
	for running {
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.QuitEvent:
				running = false
			case *sdl.KeyboardEvent:
				if e.Type == sdl.KEYDOWN {
					running = gs.HandleKey(e.Keysym.Sym)
				}
			}
		}

		now := sdl.GetTicks()
		delta := now - lastTime
		lastTime = now

		gs.Update(delta)

		gl.Clear(gl.COLOR_BUFFER_BIT)
		font.Draw(5, 5, fmt.Sprintf("Level: %d | Score: %d", gs.Level, gs.Score))
		gs.Draw()
		gl.Color3ub(255, 255, 255)
		sdl.GL_SwapBuffers()
	}
}
예제 #11
0
func main() {

	filename = flag.String("file", "testbed/data/dude.dat", "enter filename path")
	cx = flag.Int("cx", 300, "enter x-coordinate center")
	cy = flag.Int("cy", 500, "enter y-coordinate center")
	zoom = flag.Float64("zoom", 2, "enter zoom")

	flag.Parse()

	fmt.Println("opening...", *filename)
	f, err := os.Open(*filename)
	if f == nil {
		fmt.Fprintf(os.Stderr, "cat: can't open %s: error %s\n", *filename, err)
		os.Exit(1)
	}

	d, _ := ioutil.ReadAll(f)
	line := strings.SplitAfter(string(d), "\n")

	j := 0
	for i := 0; i < len(line); i++ {
		if len(line[i]) <= 2 {
			break
		}
		j++
	}

	var polyline = make(p2t.PointArray, j)
	for i := 0; i < j; i++ {
		line[i] = strings.TrimRight(line[i], "\r\n")
		num := strings.Split(line[i], " ")
		n1, err1 := strconv.Atof64(num[0])
		n2, err2 := strconv.Atof64(num[1])
		if err1 != nil || err2 != nil {
			fmt.Fprintf(os.Stderr, "cat: can't open %s: error %s\n", *filename, err)
			os.Exit(1)
		}
		polyline[i] = &p2t.Point{X: n1, Y: n2}
	}

	f.Close()

	left = -Width / float64(*zoom)
	right = Width / float64(*zoom)
	bottom = -Height / float64(*zoom)
	top = Height / float64(*zoom)

	last_time := time.Nanoseconds()

	p2t.Init(polyline)
	var triangles p2t.TriArray = p2t.Triangulate()

	dt := time.Nanoseconds() - last_time
	fmt.Printf("Elapsed time : %f ms\n", float64(dt)*1e-6)

	//var mesh p2t.TriArray = p2t.Mesh()

	sdl.Init(sdl.INIT_VIDEO)

	var screen = sdl.SetVideoMode(Width, Height, 16, sdl.OPENGL|sdl.RESIZABLE)

	if screen == nil {
		sdl.Quit()
		panic("Couldn't set GL video mode: " + sdl.GetError() + "\n")
	}

	sdl.WM_SetCaption("Pol2tri - testbed", "poly2tri")

	if gl.Init() != 0 {
		panic("gl error")
	}

	initGL()

	done := false
	for !done {
		for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
			switch e.(type) {
			case *sdl.ResizeEvent:
				re := e.(*sdl.ResizeEvent)
				screen = sdl.SetVideoMode(int(re.W), int(re.H), 16,
					sdl.OPENGL|sdl.RESIZABLE)
				if screen != nil {
					reshape(int(screen.W), int(screen.H))
				} else {
					panic("we couldn't set the new video mode??")
				}
				break

			case *sdl.QuitEvent:
				done = true
				break
			}
		}
		keys := sdl.GetKeyState()

		if keys[sdl.K_ESCAPE] != 0 {
			done = true
		}
		resetZoom()
		draw(triangles)
	}
	sdl.Quit()
	return

}
예제 #12
0
func MainGame(lvl int) int {
	//=================================
	//Init Stuff
	//=================================
	if player == nil {
		player = NewPlayer()
	}
	currentLvl = MapList[lvl]()
	currentLvl.CreateSurface(screen)
	lasers := Lasers{}
	elasers := Lasers{}
	timer := GameTime{now(), now() + int64(currentLvl.TimeLimit*1e9)}
	var WinDelay int64

	DeltaTime = now() - 50e6
	for running := true; running; {
		Refresh(screen)
		//=================================
		//Events
		//=================================
		for ev := sdl.PollEvent(); ev != nil; ev = sdl.PollEvent() {
			switch e := ev.(type) {
			case *sdl.QuitEvent:
				return G_EXITPROGRAM
				/*
				   case *sdl.KeyboardEvent:
				   	if e.Type == sdl.KEYDOWN && e.Keysym.Sym == sdl.K_p {
				   		d := difftime(DeltaTime)
				   		for PressKey() != sdl.K_p {
				   		}
				   		DeltaTime = now()-d
				   	}*/
			}
		}

		if fps() < 20 {
			DeltaTime = now()
			continue
		}

		//=================================
		//Object Events
		//=================================
		gravity.Y = GRAVITYCONSTANT / fps2()

		player.Events()
		lasers = lasers.Clean()
		elasers = elasers.Clean()
		currentLvl.Objs = currentLvl.Objs.Clean()

		if sdl.GetKeyState()[sdl.K_SPACE] != 0 {
			t := player.Shoot()
			if t != nil {
				lasers = append(lasers, t)
			}
		}

		for _, v := range currentLvl.Monst.Attack() {
			elasers = append(elasers, v)
		}

		//=================================
		//Moving Objects
		//=================================
		player.Move()
		currentLvl.Monst.Move()
		currentLvl.Objs.Move()
		lasers.Move()
		elasers.Move()

		//=================================
		//Collission
		//=================================
		for im := 0; im < len(currentLvl.Monst); im++ {
			mon := currentLvl.Monst[im]
			for il := 0; il < len(lasers); il++ {
				las := lasers[il]
				if HitTest(mon, las) {
					if mon.Damage(las.Damage()) { //if dies
						//Spoils
						spoil := NewSpoils(mon.GetRect().X, mon.GetRect().Y)
						if !spoil.IsDead() {
							currentLvl.Objs = append(currentLvl.Objs, spoil)
						}
						//Removing
						currentLvl.Monst = currentLvl.Monst.Remove(im)
						im--

					}
					lasers = lasers.Remove(il)
					il--
				}
			}
		}

		if !player.IsImmortal() {
			for _, v := range currentLvl.Monst {
				if HitTest(player, v) {
					player.WasHit()
				}
			}
			for _, v := range elasers {
				if HitTest(player, v) {
					player.WasHit()
				}
			}
		}

		lasers = lasers.HitWall(currentLvl)

		currentLvl.Objs.Hit(player)

		DeltaTime = now()
		//=================================
		//Blitting
		//=================================
		currentLvl.Blit(screen)
		player.Blit(screen)
		currentLvl.Monst.Blit(screen)
		currentLvl.Objs.Blit(screen)
		lasers.Blit(screen)
		elasers.Blit(screen)
		BlitHeartsAndTimer(screen, player.Lives, timer)

		//=================================
		//Win Lose Conditions
		//=================================
		if WinDelay == 0 {
			if player.Lives == 0 || difftime(timer.End) > 0 {
				if len(currentLvl.Monst) != 0 {
					return G_GAMEOVER
				}
			}
			if len(currentLvl.Monst) == 0 {
				WinDelay = now() + 2e9
			}
		} else if now()-WinDelay > 0 {
			if lvl == len(MapList)-1 {
				return G_ENDGAME
			}
			return G_NEXTLEVEL
		}
		//=================================
		//FrameSetting
		//=================================
		screen.Flip()
		f := now() - DeltaTime
		if f/1e6 < 30 {
			sdl.Delay(uint32(30 - (f / 1e6)))
		}
	}
	return G_NEXTLEVEL
}
예제 #13
0
func main() {
	//Make sure that resources get released
	defer g_engine.Exit()

	//Permission to run on 2 CPU cores
	runtime.GOMAXPROCS(2)

	//Initialize SDL
	err := sdl.Init()
	if err != "" {
		fmt.Printf("Error in Init: %v", err)
		return
	}

	//Initialize the engine
	g_engine.Init()

	//Load data
	g_game.LoadFonts()
	Draw() //Draw the "please wait" text after loading the fonts
	g_game.LoadGuiImages()
	g_game.LoadTileImages()
	g_game.LoadCreatureImages()
	g_game.SetState(GAMESTATE_LOGIN)

	g_loginControls.Show()

	lastTime := sdl.GetTicks()

	frameTime := sdl.GetTicks()
	frameCount := 0

	//Handle events 
	for g_running {
		for {
			event, present := sdl.PollEvent()
			if present {
				EventHandler(event)
			} else {
				break
			}
		}

		//Render everything on screen
		Draw()

		//Give the CPU some time to do other stuff
		sdl.Delay(1)

		//Handle a network message
		g_conn.HandleMessage()

		//Handle a battle event
		if g_game.state == GAMESTATE_BATTLE {
			g_game.battle.ProcessEvents()
		}

		//Update frame time 
		g_frameTime = sdl.GetTicks() - lastTime
		lastTime = sdl.GetTicks()

		//Update FPS
		frameCount++
		if sdl.GetTicks()-frameTime >= 1000 {
			g_FPS = frameCount
			frameCount = 0
			frameTime = sdl.GetTicks()
		}
	}
	sdl.Quit()
}