Ejemplo n.º 1
0
func main() {
	window := sf.NewRenderWindow(
		sf.VideoMode{800, 600, 32},
		"Hallo Welt",
		sf.StyleDefault,
		sf.DefaultContextSettings(),
	)

	game := game.New()
	game.Start(window)
}
Ejemplo n.º 2
0
func NewGame(title string, width uint, height uint, bpp uint, vsync bool) *Game {
	Game := new(Game)
	Game.Width = width
	Game.Height = height
	Game.RenderWindow = sf.NewRenderWindow(sf.VideoMode{width, height, bpp}, title, sf.StyleDefault, sf.DefaultContextSettings())
	Game.RenderWindow.SetVSyncEnabled(vsync)
	Game.Font, _ = sf.NewFontFromFile("res/fonts/UbuntuMono-R.ttf")
	Game.State = 0
	Game.StartStateInit()
	Game.Textures = NewTextures("res/images/")
	return Game
}
Ejemplo n.º 3
0
func main() {
	ticker := time.NewTicker(time.Second / 30)
	setting := sf.DefaultContextSettings()
	setting.AntialiasingLevel = 8
	renderWindow := sf.NewRenderWindow(sf.VideoMode{800, 600, 32}, "Events (GoSFML2)", sf.StyleDefault, setting)

	grid, err := shapes.NewGirdShape(sf.Vector2f{500, 400}, sf.Vector2f{50, 40}, sf.ColorWhite())

	imageGot, _, err := images.ReadImage("./011.jpg", 0, 0, 500, 400)
	texture, err := images.ReadTextureFromImage(*imageGot)
	if err != nil {
		fmt.Println(err)
		return
	}
	texture.SetSmooth(true)
	grid.SetTexture(texture)
	grid.Move(sf.Vector2f{100, 100})
	grid.Rotate(15)
	var pointX, pointY int
	var gotPoint bool

	for renderWindow.IsOpen() {
		select {
		case <-ticker.C:
			mousePosi := sf.MouseGetPosition(renderWindow)
			mousePosf := sf.Vector2f{float32(mousePosi.X), float32(mousePosi.Y)}
			for event := renderWindow.PollEvent(); event != nil; event = renderWindow.PollEvent() {
				switch event.(type) {
				case sf.EventClosed:
					renderWindow.Close()
				case sf.EventMouseButtonPressed:
					pointX, pointY, gotPoint = grid.GetNearestPointIndex(mousePosf)
				}
			}
			if sf.IsMouseButtonPressed(0) {
				if gotPoint {
					grid.SmoothPointsTo(pointX, pointY, mousePosf, 10, func(data float32) float32 {
						return (mathUtil.Sin(data, -0.5, 1)/2 + 0.5) / 5
					})
				}
			}
		}
		renderWindow.Clear(sf.ColorWhite())
		renderWindow.Draw(grid, sf.DefaultRenderStates())
		renderWindow.Display()
	}
}
Ejemplo n.º 4
0
//NewGame initializes a Game struct.
func NewGame() *Game {
	g := new(Game)
	g.Settings = readSettings()
	g.window = sf.NewRenderWindow(sf.VideoMode{uint(g.resW), uint(g.resH), 32}, "GoSFMLike", sf.StyleDefault, sf.DefaultContextSettings())
	g.state = PLAY

	g.area = NewArea()
	g.player = NewEntity("player", 0, 0, 3, 4, g.area)
	g.cursor = NewEntity("cursor", 0, 0, 2, 2, g.area)

	for i := 0; i < 3; i++ {
		g.mobs = append(g.mobs, NewEntityFromFile("orc", 3+i, 1, g.area))
		g.items = append(g.items, NewEntityFromFile("potion", 4, 4, g.area))
	}
	g.mobs = append(g.mobs, g.player)

	g.gameView = sf.NewView()
	g.gameView.SetCenter(g.player.PosVector())
	g.gameView.SetSize(sf.Vector2f{g.resW * 0.75, g.resH * 0.75})
	g.gameView.SetViewport(sf.FloatRect{0, 0, .75, .75})

	g.statusView = sf.NewView()
	g.statusView.SetSize(sf.Vector2f{g.resW * 0.25, g.resH})
	g.statusView.SetCenter(sf.Vector2f{(g.resW * 0.25) / 2, g.resH / 2})
	g.statusView.SetViewport(sf.FloatRect{.77, 0, .25, 1})

	g.hpText, _ = sf.NewText(Font)
	g.hpText.SetCharacterSize(12)

	g.logView = sf.NewView()

	var err error
	g.lookText, err = sf.NewText(Font)
	if err != nil {
		panic(err)
	}
	g.lookText.SetCharacterSize(12)

	g.logText, _ = sf.NewText(Font)
	g.logText.SetCharacterSize(12)

	return g
}
Ejemplo n.º 5
0
func main() {
	//Define some variables for the game
	//This block mostly will not change
	paddleMaxSpeed := float32(400.0)
	paddleDefaultSize := sf.Vector2f{25, 100}
	isPlaying := false

	gameWidth := uint(800)
	gameHeight := uint(600)
	bitDepth := uint(32)

	ballMaxSpeed := float32(400.0)
	ballRadius := float32(10.0)

	//These are a little more special... guess what they do!
	ticker := time.NewTicker(time.Second / 60)
	aiTicker := time.NewTicker(time.Second / 10)
	rand.Seed(time.Now().UnixNano())

	//Instantiate the render window for SFML
	renderWindow := sf.NewRenderWindow(sf.VideoMode{gameWidth, gameHeight, bitDepth}, "Pong (Brett's Go test)", sf.StyleDefault, nil)

	//Create the left paddle
	leftPaddle := paddle.NewPaddle(paddleMaxSpeed, paddleMaxSpeed, paddleDefaultSize, sf.Color{100, 100, 200, 255})

	//Create the right paddle
	rightPaddle := paddle.NewPaddle(0, paddleMaxSpeed, paddleDefaultSize, sf.Color{200, 100, 100, 255})

	//Create the ball
	ball := ball.NewBall(ballMaxSpeed, ballMaxSpeed, ballRadius, "resources/ball.wav")

	//Load font
	font, _ := sf.NewFontFromFile("resources/sansation.ttf")

	//Init the pause message
	pauseMessage := sf.NewText(font)
	pauseMessage.SetCharacterSize(40)
	pauseMessage.SetPosition(sf.Vector2f{170, 150})
	pauseMessage.SetColor(sf.ColorWhite())
	pauseMessage.SetString("Welcome to Brett's SFML Pong!\nPress space to start the game.")

	for renderWindow.IsOpen() {
		select {
		case <-ticker.C:
			//poll for events
			for event := renderWindow.PollEvent(); event != nil; event = renderWindow.PollEvent() {
				switch ev := event.(type) {
				case sf.EventKeyReleased:
					switch ev.Code {
					case sf.KeyEscape:
						renderWindow.Close()
					case sf.KeySpace:
						if !isPlaying {
							//restart the game
							isPlaying = true
							leftPaddle.Shape.SetPosition(sf.Vector2f{10 + leftPaddle.Size.X/2, float32(gameHeight) / 2})
							rightPaddle.Shape.SetPosition(sf.Vector2f{float32(gameWidth) - 10 - rightPaddle.Size.X/2, float32(gameHeight) / 2})
							ball.Shape.SetPosition(sf.Vector2f{float32(gameWidth) / 2, float32(gameHeight) / 2})

							//ensure the ball angle isn't too vertical
							for {
								ball.Angle = rand.Float32() * math.Pi * 2

								if math.Abs(math.Cos(float64(ball.Angle))) > 0.7 {
									break
								}
							}
						}
					}
				case sf.EventClosed:
					renderWindow.Close()
				}
			}

			if isPlaying {
				deltaTime := time.Second / 60

				//Move the player's paddle
				if sf.KeyboardIsKeyPressed(sf.KeyUp) && leftPaddle.TopLeft().Y > 5 {
					leftPaddle.Shape.Move(sf.Vector2f{0, -leftPaddle.Speed * float32(deltaTime.Seconds())})
				}
				if sf.KeyboardIsKeyPressed(sf.KeyDown) && leftPaddle.BottomRight().Y < float32(gameHeight)-5 {
					leftPaddle.Shape.Move(sf.Vector2f{0, leftPaddle.Speed * float32(deltaTime.Seconds())})
				}

				//Move the ai's paddle
				if (rightPaddle.Speed < 0 && rightPaddle.TopLeft().Y > 5) || (rightPaddle.Speed > 0 && rightPaddle.BottomRight().Y < float32(gameHeight)-5) {
					rightPaddle.Shape.Move(sf.Vector2f{0, rightPaddle.Speed * float32(deltaTime.Seconds())})
				}

				//Move ze ball
				factor := ball.Speed * float32(deltaTime.Seconds())
				ball.Shape.Move(sf.Vector2f{float32(math.Cos(float64(ball.Angle))) * factor, float32(math.Sin(float64(ball.Angle))) * factor})

				//Check collisions between ball and screen edge
				if ball.TopLeft().X < 0 {
					isPlaying = false
					pauseMessage.SetString("You lost!\nPress space to restart or\nescape to quit")
				}

				if ball.BottomRight().X > float32(gameWidth) {
					isPlaying = false
					pauseMessage.SetString("You won!\nPress space to play again or\nescape to quit")
				}

				if ball.TopLeft().Y < 0 {
					ball.Angle = -ball.Angle
					ball.Shape.SetPosition(sf.Vector2f{ball.Center().X, ball.Radius + 0.1})
					ball.Sound.Play()
				}

				if ball.BottomRight().Y > float32(gameHeight) {
					ball.Angle = -ball.Angle
					ball.Shape.SetPosition(sf.Vector2f{ball.Center().X, float32(gameHeight) - ball.Radius - 0.1})
					ball.Sound.Play()
				}

				//Check collisions between the ball and the left paddle
				if leftPaddle.CollideRight(ball) {

					if ball.Center().Y > leftPaddle.Center().Y {
						ball.Angle = math.Pi - ball.Angle + rand.Float32()*math.Pi*0.2
					} else {
						ball.Angle = math.Pi - ball.Angle - rand.Float32()*math.Pi*0.2
					}

					ball.Shape.SetPosition(sf.Vector2f{leftPaddle.Center().X + ball.Radius + leftPaddle.Size.X/2 + 0.1, ball.Center().Y})
					ball.Sound.Play()
				}

				//Check collisions between the ball and the right paddle
				if rightPaddle.CollideLeft(ball) {

					if ball.Center().Y > rightPaddle.Center().Y {
						ball.Angle = math.Pi - ball.Angle + rand.Float32()*math.Pi*0.2
					} else {
						ball.Angle = math.Pi - ball.Angle - rand.Float32()*math.Pi*0.2
					}

					ball.Shape.SetPosition(sf.Vector2f{rightPaddle.Center().X - ball.Radius - rightPaddle.Size.X/2 - 0.1, ball.Center().Y})
					ball.Sound.Play()
				}
			}

			//Clear the window
			renderWindow.Clear(sf.Color{50, 200, 50, 0})

			//Draw some shit
			if isPlaying {
				renderWindow.Draw(leftPaddle.Shape, nil)
				renderWindow.Draw(rightPaddle.Shape, nil)
				renderWindow.Draw(ball.Shape, nil)
			} else {
				renderWindow.Draw(pauseMessage, nil)
			}

			//Draw everything to the screen
			renderWindow.Display()

		case <-aiTicker.C:
			if ball.BottomRight().Y > rightPaddle.BottomRight().Y {
				rightPaddle.Speed = rightPaddle.MaxSpeed
			} else if ball.TopLeft().Y < rightPaddle.TopLeft().Y {
				rightPaddle.Speed = -rightPaddle.MaxSpeed
			} else {
				rightPaddle.Speed = 0
			}
		}
	}

}
Ejemplo n.º 6
0
func main() {

	if len(os.Args) < 3 {
		fmt.Println("add the color range function: operiation x ,like + 2 ")
		return
	}

	colorRangeFunc := func(r, g, b, anivalue float32) (outr, outg, outb float32) {
		if os.Args[len(os.Args)-1] != "a" {
			anivalue = 0
		}
		outr = argsCheckAndAddColor(r, 1, anivalue)
		outg = argsCheckAndAddColor(g, 2, anivalue)
		outb = argsCheckAndAddColor(g, 3, anivalue)
		return
	}

	ticker := time.NewTicker(time.Second / 30)
	setting := sf.DefaultContextSettings()
	setting.AntialiasingLevel = 8
	renderWindow := sf.NewRenderWindow(sf.VideoMode{800, 600, 32}, "Events (GoSFML2)", sf.StyleDefault, setting)

	round, err := sf.NewCircleShape()

	imageGot, _, err := images.ReadImage("./011.jpg", -50, -50, 600, 600)
	if err != nil {
		fmt.Println(err)
		return
	}
	imageGot__ := images.ImageEnhanceRGBWithFunc(imageGot, func(r, g, b float32) (outr, outg, outb float32) {
		outr = 127 * float32(math.Sin(float64(r-127)/255*math.Pi+1))
		outg = g
		outb = b
		return
	})
	texture, err := images.ReadTextureFromImage(*imageGot__)
	if err != nil {
		fmt.Println(err)
		return
	}
	texture.SetSmooth(true)
	round.SetPosition(sf.Vector2f{100, 50})
	round.SetRadius(300)
	round.SetTexture(texture, true)

	clip := animations.NewLoopAnimation([]float32{0}, []float32{255}, -1, animations.Pingpong, func(values []float32) {
		imageGot__ = images.ImageEnhanceRGBWithFunc(imageGot, func(r, g, b float32) (outr, outg, outb float32) {
			outr, outg, outb = colorRangeFunc(r, g, b, values[0])
			return
		})
		texture, _ := images.ReadTextureFromImage(*imageGot__)
		round.SetTexture(texture, true)
	}, nil)
	clip.SetFrameCount(60)
	animation := animations.NewAnimation(0)
	animation.AddClip(clip)
	animation.Play()
	for renderWindow.IsOpen() {
		select {
		case <-ticker.C:
			for event := renderWindow.PollEvent(); event != nil; event = renderWindow.PollEvent() {
				switch event.(type) {
				case sf.EventClosed:
					renderWindow.Close()
				}
			}
		}
		animation.Animate()
		renderWindow.Clear(sf.ColorWhite())
		renderWindow.Draw(round, sf.DefaultRenderStates())
		renderWindow.Display()
	}
}
Ejemplo n.º 7
0
func main() {
	ticker := time.NewTicker(time.Second / 30)
	setting := sf.DefaultContextSettings()
	setting.AntialiasingLevel = 8
	renderWindow := sf.NewRenderWindow(sf.VideoMode{800, 600, 32}, "Events (GoSFML2)", sf.StyleDefault, setting)

	shape, _ := shapeEX.NewCurveCicleShape(10, 100, 8)
	shape.SetFillColor(sf.Color{255, 100, 55, 255})

	animation1 := animations.NewAnimation(1)
	clip10 := animations.NewSingleAnimationClip(
		shape.GetPosition(),
		sf.Vector2f{500, 200},
		func(step interface{}) {
			stepv2, _ := step.(sf.Vector2f)
			shape.SetPosition(stepv2)
		}, func() {
		})
	clip11 := animations.NewSingleAnimationClip(
		sf.Vector2f{500, 200},
		sf.Vector2f{200, 400},
		func(step interface{}) {
			stepv2, _ := step.(sf.Vector2f)
			shape.SetPosition(stepv2)
		}, func() {
		})
	clip10.SetFrameCount(120)
	clip11.SetFrameCount(120)
	animation1.AddClip(clip10)
	animation1.AddClip(clip11)

	animation2 := animations.NewAnimation(1)
	clip20 := animations.NewLoopAnimation(
		0.2, 1.8, -1, animations.Pingpong,
		func(step interface{}) {
			stepv1, _ := step.(float32)
			for i := 0; i < 8; i++ {
				if i%2 == 0 {
					shape.ExpendPointTo(uint(i), stepv1)
				}

			}
		}, func() {
		})
	clip20.SetAnimationCurve(func(num float32) float32 {
		return num * num
	})
	clip20.SetFrameCount(20)
	animation2.AddClip(clip20)

	animation1.Play()
	animation2.Play()
	for renderWindow.IsOpen() {
		select {
		case <-ticker.C:
			for event := renderWindow.PollEvent(); event != nil; event = renderWindow.PollEvent() {
				switch event.(type) {
				case sf.EventClosed:
					renderWindow.Close()
				}
			}
		}
		animation1.Animate()
		animation2.Animate()
		renderWindow.Clear(sf.ColorWhite())
		renderWindow.Draw(shape, sf.DefaultRenderStates())
		renderWindow.Display()
	}
}
Ejemplo n.º 8
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	runtime.LockOSThread()

	flag.Parse()

	if showHelp {
		flag.Usage()
		return
	}

	if len(flag.Args()) != 1 {
		fmt.Println(flag.Args())
		fmt.Println("Please supply a ROM to load")
		return
	}
	filename = flag.Arg(0)

	if !debugEnabled {
		log.SetOutput(ioutil.Discard)
	}

	rom, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Println(err)
		fmt.Printf("Unable to open \"%s\"\n", filename)
		return
	}

	if len(rom) < 0x0150 {
		log.Println("Rom is too small")
		fmt.Println("Invalid ROM")
		return
	}

	var checksum uint16
	for i, b := range rom {
		if i != 0x14E && i != 0x14F {
			checksum += uint16(b)
		}
	}
	log.Printf("Checksum: 0x%04X", checksum)
	if ((uint16(rom[0x14E]) << 8) | uint16(rom[0x14F])) != checksum {
		log.Println("The ROM's checksum does not match")
	}

	gameName := string(rom[0x0134:0x0144])
	if p := strings.Index(gameName, "\000"); p != -1 {
		gameName = gameName[0:p]
	}
	log.Println("Name of the game:", gameName)

	log.Printf("ROM type: 0x%02X", rom[0x0148])
	var romSize int
	switch rom[0x0148] {
	case 0x0:
		romSize = 32 * 1024
		log.Println("256Kbit = 32KByte = 2 banks")
	case 0x1:
		romSize = 64 * 1024
		log.Println("512Kbit = 64KByte = 4 banks")
	case 0x2:
		romSize = 128 * 1024
		log.Println("1Mbit = 128KByte = 8 banks")
	case 0x3:
		romSize = 256 * 1024
		log.Println("2Mbit = 256KByte = 16 banks")
	case 0x4:
		romSize = 512 * 1024
		log.Println("4Mbit = 512KByte = 32 banks")
	case 0x5:
		romSize = 1024 * 1024
		log.Println("8Mbit = 1MByte = 64 banks")
	case 0x6:
		romSize = 2 * 1024 * 1024
		log.Println("16Mbit = 2MByte = 128 banks")
	case 0x7:
		romSize = 4 * 1024 * 1024
		log.Println("32Mbit = 4MByte = 256 banks")
	case 0x8:
		romSize = 8 * 1024 * 1024
		log.Println("64Mbit = 8MByte = 512 banks")
	case 0x52:
		romSize = 1179648
		log.Println("9Mbit = 1.1MByte = 72 banks")
	case 0x53:
		romSize = 1310720
		log.Println("10Mbit = 1.2MByte = 80 banks")
	case 0x54:
		romSize = 1572864
		log.Println("12Mbit = 1.5MByte = 96 banks")
	default:
		log.Println("Unknown ROM size")
	}
	log.Printf("ROM is %d bytes", romSize)
	log.Printf("RAM type: 0x%02X", rom[0x0149])

	var ramSize int
	switch rom[0x0149] {
	case 0x0:
		ramSize = 0
		log.Println("None")
	case 0x1:
		ramSize = 2 * 1024
		log.Println("16kBit = 2kB = 1 bank")
	case 0x2:
		ramSize = 8 * 1024
		log.Println("64kBit = 8kB = 1 bank")
	case 0x3:
		ramSize = 32 * 1024
		log.Println("256kBit = 32kB = 4 banks")
	case 0x4:
		ramSize = 128 * 1024
		log.Println("1MBit = 128kB = 16 banks")
	default:
		var ramBanks int = int(math.Pow(4, float64(int(rom[0x0149])-0x2)))
		log.Println("Unknown RAM size, using formula")
		ramSize = ramBanks * 8 * 1024
	}

	log.Printf("RAM is %d bytes", ramSize)
	ram := make([]uint8, ramSize)

	log.Printf("Cartridge type: 0x%02X", rom[0x0147])

	mbc, mbcName, err := memory.MbcType(rom[0x0147], rom, ram)
	if err != nil {
		fmt.Println(err)
		return
	}
	log.Println(mbcName)

	m := memory.NewMMC(mbc)
	video := m.Video
	cpu := lr35902.NewCPU(m)

	if turbo {
		cpu.RealisticSteps = false
	}

	if m.Bios, err = ioutil.ReadFile("DMG_ROM.bin"); err == nil {
		log.Println("BIOS file found, loading...")
		m.BiosEnabled = true
	} else {
		log.Println("BIOS file not found, emulating state after BIOS")

		cpu.BC = 0x0013
		cpu.DE = 0x00D8
		cpu.HL = 0x014D
		cpu.PC = 0x0100
		cpu.A = 0x01
		cpu.Flags.Z = true
		cpu.Flags.H = true
		cpu.Flags.C = true
	}

	window := sf.NewRenderWindow(sf.VideoMode{160, 144, 32}, "Goboy", sf.StyleDefault, nil)
	texture, _ := sf.NewTexture(memory.WIDTH, memory.HEIGHT)
	renderingSprite := sf.NewSprite(texture)
	window.Clear(sf.ColorWhite())
	window.Display()

	screenUpdates := make(chan []uint8)
	go func() {

		for !cpu.Stopped {
			start := time.Now()
			cycles := cpu.Step()
			if cpuDump {
				cpu.DumpState()
			}
			for i := uint(0); i < cycles; i++ {
				video.Step()
				if video.LY == 144 && video.CycleStep == 0 {
					screenUpdates <- video.Pixels
				}
			}
			timeItShouldHaveTaken := int64((float64(cycles) / float64(cpu.ClockSpeed)) * 1e9)
			timeItTook := time.Now().Sub(start).Nanoseconds()
			if cpu.RealisticSteps {
				if timediff := timeItShouldHaveTaken - timeItTook; timediff > 0 {
					log.Printf("Sleeping for %d", timediff)
					time.Sleep(time.Duration(timediff) * time.Nanosecond)
				}
			}
		}
	}()
main:
	for {
		t := <-screenUpdates
		texture.UpdateFromPixels(t, memory.WIDTH, memory.HEIGHT, 0, 0)
		// VBLANK interrupt & render
		window.Clear(sf.ColorWhite())
		window.Draw(renderingSprite, nil)
		window.Display()
		for event := window.PollEvent(); event != nil; event = window.PollEvent() {
			switch ev := event.(type) {
			case sf.EventKeyPressed:
				//exit on ESC
				if ev.Code == sf.KeyEscape {
					break main
				}
			case sf.EventClosed:
				break main
			}
		}
	}
	cpu.DumpState()
}