Exemplo n.º 1
0
func (w *Window) Repaint() error {

	w.Lock()
	err := termbox.Clear(w.Fg, w.Bg)
	width, height := termbox.Size()

	if err != nil {
		return err
	}

	for _, row := range w.Widgets[w.scrollPos:] {
		j := 0
		for _, c := range row.Text {

			termbox.SetCell(w.x, w.y, rune(c), row.Fg[j], row.Bg[j])
			j++

			if w.x += 1; w.x > width {
				break
			}
		}
		w.x = 0

		if w.y += 1; w.y > height {
			break
		}
	}
	w.y = 0
	w.x = 0

	w.Unlock()
	return nil
}
Exemplo n.º 2
0
Arquivo: form.go Projeto: telyn/form
func (f *Form) Run() error {
	draw := func() bool {
		termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
		f.DrawInto(&box.TermBox{}, 0, 0)

		termbox.Flush()
		return true
	}
	err := termbox.Init()
	defer termbox.Close()
	if err != nil {
		return err
	}

	if draw() {
		f.running = true
		for f.running {
			ev := termbox.PollEvent()
			if !f.HandleEvent(&ev) {
				f.running = false
			}
			draw()
		}
	} else {
		return errors.New("fail sadness")
	}
	return nil
}
Exemplo n.º 3
0
func main() {
	err := tb.Init()
	if err != nil {
		panic(err)
	}
	defer tb.Close()

	tb.SetInputMode(tb.InputEsc)
	tb.Clear(tb.ColorCyan, tb.ColorBlue)
	tb.Flush()

loop:
	for i := 0; ; i++ {
		ev := tb.PollEvent()
		switch ev.Type {
		case tb.EventKey:
			if ev.Key == tb.KeyCtrlC {
				break loop
			}
			tb.SetCell(i, i, ev.Ch, tb.ColorGreen, tb.ColorBlack)
			tb.Flush()
		case tb.EventError:
			panic(ev.Err)
		}
	}
}
Exemplo n.º 4
0
Arquivo: main.go Projeto: telyn/form
func draw() bool {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)

	dots := NewCellsBox([]termbox.Cell{dot, dot, dot, dot, dot,
		dot, dot, dot, dot, dot,
		dot, dot, dot, dot, dot,
		dot, dot, dot, dot, dot,
	}, 5)

	greenPlus := NewCellsBox([]termbox.Cell{greenPlus, greenPlus, greenPlus, greenPlus}, 2)

	if err := greenPlus.DrawInto(dots, 1, 2); err != nil {
		termbox.Close()
		fmt.Fprintf(os.Stderr, "%v1\r\n", err)
		return false
	}
	if err := dots.DrawInto(&TermBox{}, 0, 0); err != nil {
		termbox.Close()
		fmt.Fprintf(os.Stderr, "%v2\r\n", err)
		return false
	}

	termbox.SetCell(0, 0, '+', termbox.ColorRed, termbox.ColorDefault)
	termbox.SetCell(1, 0, '+', termbox.ColorRed, termbox.ColorDefault)
	termbox.SetCell(7, 0, '+', termbox.ColorRed, termbox.ColorDefault)

	termbox.Flush()
	return true
}
Exemplo n.º 5
0
func (s *Session) Run() error {
	s.mode = &ModeEdit{}
	data, err := ioutil.ReadFile(s.File)
	if err != nil {
		return err
	}
	s.Buf = util.NewBuffer(data)
	s.W, s.H = termbox.Size()
	s.H--
	s.View.SetBuf(s.Buf)
	s.View.SetSize(s.W, s.H)
	s.View.SetTabwidth(s.Tabwidth)

	for {
		s.Draw()
		termbox.Flush()
		termbox.Clear(0, 0)

		ev := termbox.PollEvent()
		switch ev.Type {
		case termbox.EventKey:
			s.mode, err = s.mode.HandleKey(s, ev)
			if err != nil {
				return err
			}
		case termbox.EventResize:
			s.W, s.H = ev.Width, ev.Height-1
			s.View.SetSize(s.W, s.H)
		case termbox.EventMouse:
		case termbox.EventError:
			return ev.Err
		}
	}
}
Exemplo n.º 6
0
/* A multiplayer rogue-like in the spirit of TOAG, but implemented in termbox-go */
func main() {

	//flag.Parse()
	/* start network handling and channels */
	max_dimensions := 80 * 24
	screen := make([]nr.Sprite, max_dimensions)
	world := loadWorld()

	/* initialize termbox interface */
	err := tb.Init()
	check(err)

	tb.SetInputMode(tb.InputAlt)
	w, h := tb.Size()

	tb.Clear(tb.ColorBlack, tb.ColorBlack)
	tb.Flush()
	go draw(w, h)

	for run := true; run == true; {
		switch ev := tb.PollEvent(); ev.Type {
		case tb.EventKey:
			//key := ev.Ch
			if ev.Key == tb.KeyCtrlQ {
				tb.Flush()
				run = false
			}
		default:
		}
	}
}
Exemplo n.º 7
0
Arquivo: main.go Projeto: telyn/form
func draw() bool {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
	labelField.DrawInto(&box.TermBox{}, 0, 0)

	termbox.Flush()
	return true
}
Exemplo n.º 8
0
func clear(fg, bg termbox.Attribute) error {
	mutex.Lock()
	err := termbox.Clear(fg, bg)
	mutex.Unlock()
	updateRootBuffer()
	return err
}
Exemplo n.º 9
0
// Repaints everything on the screen
func RefreshScreen() {
	term.Clear(ColorWhite, ColorBlack)

	for _, wnd := range comp.windows {
		wnd.Draw()
	}

	term.Flush()
}
Exemplo n.º 10
0
// Render renders all Bufferer in the given order from left to right,
// right could overlap on left ones.
func Render(rs ...Bufferer) {
	tm.Clear(tm.ColorDefault, toTmAttr(theme.BodyBg))
	for _, r := range rs {
		buf := r.Buffer()
		for _, v := range buf {
			tm.SetCell(v.X, v.Y, v.Ch, toTmAttr(v.Fg), toTmAttr(v.Bg))
		}
	}
	tm.Flush()
}
Exemplo n.º 11
0
func drawDrumMachine() {
	tb.Clear(tb.ColorDefault, tb.ColorDefault)
	term.ofs.seq = drawHeader()
	if term.mode == newModePickSample || term.mode == newModeEnterName {
		term.ofs.trk = drawSamples()
	} else {
		term.ofs.trk = drawSequences()
		drawSections()
	}
	tb.Flush()
}
Exemplo n.º 12
0
Arquivo: main.go Projeto: telyn/form
func draw() bool {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)

	termbox.SetCell(0, 0, 'H', 0, 0)
	termbox.SetCell(1, 0, 'e', 0, 0)
	termbox.SetCell(2, 0, 'y', 0, 0)
	textField.DrawInto(&box.TermBox{}, 4, 0)

	termbox.Flush()
	return true
}
Exemplo n.º 13
0
func (tb termboxImpl) WaitEvent() bool {
	switch ev := tb.proxy(); ev.Type { // PollEvent will be blocked
	case termbox.EventKey:
		if ev.Key == termbox.KeyEsc {
			return true
		}
	case termbox.EventResize:
		termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
	case termbox.EventError:
		panic(ev.Err)
	}
	return false
}
Exemplo n.º 14
0
func main() {
	termbox.Init()
	defer termbox.Close()

	et, err := gaze.AnyEyeTracker()

	if err != nil {
		log.Println(err)
		return
	}

	et.Connect()
	defer et.Close()
	termbox.Clear(0, termbox.ColorWhite) //Set bg to white.
	et.StartTracking(func(data *gaze.GazeData) {
		ts := data.TrackingStatus()
		if ts >= gaze.BothEyesTracked && ts != gaze.OneEyeTrackedUnknownWhich {
			termbox.Clear(0, termbox.ColorWhite)
			drawPoint(*data.Left().GazePointOnDisplay(), leftMarker)
			drawPoint(*data.Right().GazePointOnDisplay(), rightMarker)
			termbox.Flush()
		}
	})

	done := make(chan struct{})

	go func() {
		for {
			event := termbox.PollEvent()
			if event.Type == termbox.EventKey && event.Key == termbox.KeyEsc {
				close(done)
			}
		}
	}()

	<-done
}
Exemplo n.º 15
0
func calibratePoint(et gaze.EyeTracker, x, y float64) {
	termbox.Clear(0, 0)
	sizeX, sizeY := termbox.Size()
	dx, dy := int(float64(sizeX)*x), int(float64(sizeY)*y)
	termbox.CellBuffer()[sizeX*dy+dx] = termbox.Cell{'#', marker, termbox.ColorDefault}
	termbox.Flush()
	//log.Printf("Termbox Size: (%d, %d)", sizeX, sizeY)
	log.Printf("Calibrating (%.3f, %.3f)", x, y)
	done := make(chan struct{})
	time.Sleep(1 * time.Second) //Minimum time. Gives user time to react.
	et.AddPointToCalibration(gaze.NewPoint2D(x, y), func(err error) {
		close(done) //Synchronizing async call.
	})
	<-done
}
Exemplo n.º 16
0
// Display the baord
// b1 our board = b2 their board
func Display(b1, b2 TheirBoard, writer io.Writer) {

	fmt.Println("Display")

	// Clear the terminal
	termbox.Clear(termbox.ColorWhite, termbox.ColorBlack)

	xStart := 10
	yStart := 10

	print_tb(5, 5, "Battle Ships", termbox.ColorMagenta, termbox.ColorWhite)

	printBoard(b1, xStart, yStart)
	printBoard(b2, xStart+30, yStart)

}
Exemplo n.º 17
0
func (this *Game) Draw() {
	tb.Clear(tb.ColorDefault, tb.ColorDefault)

	this.ForEachActivePanel(func(p *Panel) {
		p.Clear()
		p.DrawBorder()
	})

	x, y := this.Player.Position()
	this.ViewPanel.Screen.SetCell(x, y, '@', tb.ColorWhite, tb.ColorBlack)

	this.ForEachActivePanel(func(p *Panel) {
		p.Blit()
	})

	tb.Flush()
}
Exemplo n.º 18
0
func render(s state) {

	tb.Clear(tb.ColorDefault, tb.ColorDefault)

	w, h := tb.Size()

	drawString(1, 1, fmt.Sprint("dust: ", s.dust))

	if s.howManyBuilt(searcher.name) > 0 {
		drawString(1, 2, fmt.Sprint("data disks: ", s.disks))
	}

	if s.highestDust >= collector.baseCost {

		drawString(1, 3,
			fmt.Sprint(
				"[c]ollectors(", collector.currentCost(s), "): ",
				s.howManyBuilt(collector.name)))
	}

	if s.highestDust >= searcher.baseCost {

		drawString(1, 4, fmt.Sprint(
			"[s]earcher(", searcher.currentCost(s), "):  ",
			s.howManyBuilt(searcher.name)))
	}

	helpMessage := "hit [space] to take a turn, [h] for help, [q] or [Esc] to quit"
	nextTurnMessage := fmt.Sprint(
		"next turn:", getDescription(s.nextTurnEvent))

	drawString((w/2)-(len(helpMessage)/2), h-1, helpMessage)
	drawString((w/2)-(len(nextTurnMessage)/2), h-2, nextTurnMessage)

	if len(s.message) > 0 {
		drawMessage(s.message)
	}

	err := tb.Flush()

	if err != nil {
		panic(err)
	}
}
Exemplo n.º 19
0
func main() {
	rand.Seed(time.Now().UnixNano())

	dim := dimensions{10, 10}

	ships := canonicalBattleship()

	attackField := makeScatteredField(dim, ships, adversary)
	attackOrigin := coord{0, 0}
	defendField := makeScatteredField(dim, ships, human)
	defendOrigin := coord{30, 0}

	printOrigin := coord{0, 30}

	termbox.Init()
	defer termbox.Close()
	termbox.HideCursor()
	termbox.Clear(termbox.ColorBlack, termbox.ColorBlack)

	buildLabels(attackField, attackOrigin)
	buildLabels(defendField, defendOrigin)

	// game loop
	var msg_us, msg_them string
	for attackField.shipsLeft() && defendField.shipsLeft() {
		buildInnerField(attackField, attackOrigin)
		buildInnerField(defendField, defendOrigin)
		termbox.Flush()
		msg_us = move(&attackField)
		termbox.Flush()
		msg_them = counterMove(&defendField)
		tbprint(printOrigin, msg_us, termbox.ColorWhite, termbox.ColorBlack)
		tbprint(printOrigin.down(1), msg_them, termbox.ColorWhite, termbox.ColorBlack)
		termbox.Flush()
	}

	if defendField.shipsLeft() {
		fmt.Println("You've won! Congratulations.")
	} else if attackField.shipsLeft() {
		fmt.Println("You've lost!")
	}
}
Exemplo n.º 20
0
func (g *game) draw() {
	// update board and racks
	g.board.qb = g.pos().Board()
	g.rack1.player = g.playerById(0)
	g.rack2.player = g.playerById(1)
	g.w, g.h = termbox.Size()

	termbox.Clear(fgcolor, bgcolor)
	defer termbox.Flush()

	// board
	g.board.x = (g.w - g.board.w*2 + 2 + 1) / 2
	g.board.y = (g.h - g.board.h - g.rack1.h - g.editbox.h - 2) / 2
	g.board.draw()

	// racks
	g.rack1.x = g.board.x
	g.rack1.y = g.board.y + g.board.h + 2
	g.rack1.draw()
	g.rack2.x = g.board.x + g.rack1.w + 2
	g.rack2.y = g.board.y + g.board.h + 2
	g.rack2.draw()
	if g.player().Id() == 0 {
		g.rack1.setActive()
	} else {
		g.rack2.setActive()
	}

	// editbox
	g.editbox.x = g.board.x + g.editbox.w/2 + 1
	g.editbox.y = g.rack1.y - g.rack1.h + 4
	g.editbox.draw()

	// legend
	if g.showLegend {
		g.legend.x = g.board.x + g.board.w*2 - 8
		g.legend.y = g.board.y + g.board.h
		g.legend.draw()
	}
}
Exemplo n.º 21
0
func draw(img image.Image) {
	w, h := termbox.Size()
	iw, ih := img.Bounds().Max.X, img.Bounds().Max.Y
	sw, sh := fit(w, h, iw*2, ih)
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
	for y := 0; y < h; y++ {
		for x := 0; x < w; x++ {
			if x >= sw || y >= sh {
				termbox.SetCell(x, y, ' ', termbox.ColorDefault, termbox.ColorDefault)
				continue
			}
			xi := x * img.Bounds().Max.X / sw
			yi := y * img.Bounds().Max.Y / sh
			a := palette.Convert(img.At(xi, yi))
			if at, ok := a.(attrColor); ok {
				termbox.SetCell(x, y, ' ', termbox.ColorDefault,
					termbox.Attribute(at))
			}
		}
	}
	termbox.Flush()
}
Exemplo n.º 22
0
func (w *Window) Redraw() error {

	w.Lock()

	err := termbox.Clear(w.Fg, w.Bg)
	maxx, maxy := termbox.Size()

	if err != nil {
		return err
	}

	for i, row := range w.Rows[w.scrollPos:] {
		for _, c := range row.Text {

			if i == w.selected {
				termbox.SetCell(w.xpos, w.ypos, rune(c), row.Fg, row.Bg)
			} else {
				termbox.SetCell(w.xpos, w.ypos, rune(c), w.Fg, w.Bg)
			}

			if w.xpos += 1; w.xpos > maxx {
				break
			}
		}
		w.xpos = 0

		if w.ypos += 1; w.ypos > maxy {
			break
		}
	}
	w.ypos = 0
	w.xpos = 0 // redundant but lets avoid problems later

	w.Unlock()
	return nil
}
Exemplo n.º 23
0
func main() {
	// log stack
	defer func() {
		if r := recover(); r != nil {
			buf := make([]byte, 1024*1024*8)
			n := runtime.Stack(buf, true)
			errFile, err := os.Create("err.local")
			if err != nil {
				return
			}
			errFile.WriteString(fmt.Sprintf("error: %v\n\n", r))
			errFile.Write(buf[:n])
			errFile.Close()
		}
	}()
	// termbox
	err := box.Init()
	if err != nil {
		log.Fatal(err)
	}
	defer box.Close()
	go func() {
		for {
			ev := box.PollEvent()
			if ev.Type == box.EventKey {
				if ev.Key == box.KeyEsc {
					os.Exit(0)
				}
			}
		}
	}()
	// socks5 server
	socksServer, err := socks.New(globalConfig["local"])
	if err != nil {
		log.Fatal(err)
	}
	clientReader := cr.New()
	defer clientReader.Close()

	// connect to remote server
	addr, err := net.ResolveTCPAddr("tcp", globalConfig["remote"])
	if err != nil {
		log.Fatal("cannot resolve remote addr ", err)
	}
	commId := rand.Int63()
	cipherKey := []byte(globalConfig["key"])
	getServerConn := func() *net.TCPConn {
		serverConn, err := net.DialTCP("tcp", nil, addr)
		if err != nil {
			log.Fatal("cannot connect to remote server ", err)
		}
		// auth
		origin := genRandBytes(64)
		encrypted, err := encrypt(cipherKey, origin)
		if err != nil {
			log.Fatal(err)
		}
		serverConn.Write(origin)
		serverConn.Write(encrypted)
		var response byte
		err = binary.Read(serverConn, binary.LittleEndian, &response)
		if err != nil || response != byte(1) {
			log.Fatal("auth fail ", err)
		}
		// sent comm id
		binary.Write(serverConn, binary.LittleEndian, commId)
		return serverConn
	}
	comm := session.NewComm(getServerConn(), cipherKey)

	// keepalive
	keepaliveSession := comm.NewSession(-1, []byte(keepaliveSessionMagic), nil)
	keepaliveTicker := time.NewTicker(PING_INTERVAL)

	// heartbeat
	heartbeat := time.NewTicker(time.Second * 1)
	t1 := time.Now()
	delta := func() string {
		return fmt.Sprintf("%-.0fs", time.Now().Sub(t1).Seconds())
	}

	var memStats runtime.MemStats
	printer := NewPrinter(40)
	reconnectTimes := 0

loop:
	for {
		select {
		// ping
		case <-keepaliveTicker.C:
			keepaliveSession.Signal(sigPing)
		// heartbeat
		case <-heartbeat.C:
			if time.Now().Sub(comm.LastReadTime) > BAD_CONN_THRESHOLD {
				comm.UseConn(getServerConn())
				reconnectTimes += 1
			}

			box.Clear(box.ColorDefault, box.ColorDefault)
			printer.Reset()
			printer.Print("conf %s", CONFIG_FILEPATH)
			printer.Print("listening %v", globalConfig["local"])
			printer.Print("connected %v", addr)
			printer.Print("reconnected %d times", reconnectTimes)
			printer.Print("%s %s >-< %s", delta(), formatFlow(comm.BytesSent), formatFlow(comm.BytesReceived))
			runtime.ReadMemStats(&memStats)
			printer.Print("%s memory in use", formatFlow(memStats.Alloc))
			printer.Print("--- %d connections %d sessions ---", clientReader.Count, len(comm.Sessions))
			for _, sessionId := range ByValue(comm.Sessions, func(a, b reflect.Value) bool {
				return a.Interface().(*session.Session).StartTime.After(b.Interface().(*session.Session).StartTime)
			}).Interface().([]int64) {
				session := comm.Sessions[sessionId]
				serv, ok := session.Obj.(*Serv)
				if !ok {
					continue
				}
				if serv.localClosed {
					printer.Print("Lx %s", serv.hostPort)
				} else if serv.remoteClosed {
					printer.Print("Rx %s", serv.hostPort)
				} else {
					printer.Print(serv.hostPort)
				}
			}
			box.Flush()

		// new socks client
		case socksClient := <-socksServer.Clients:
			serv := &Serv{
				clientConn: socksClient.Conn,
				hostPort:   socksClient.HostPort,
			}
			serv.session = comm.NewSession(-1, []byte(socksClient.HostPort), serv)
			clientReader.Add(socksClient.Conn, serv)
		// client events
		case ev := <-clientReader.Events:
			serv := ev.Obj.(*Serv)
			switch ev.Type {
			case cr.DATA: // client data
				serv.session.Send(ev.Data)
			case cr.EOF, cr.ERROR: // client close
				if serv.session == nil { // serv already closed
					continue loop
				}
				serv.session.Signal(sigClose)
				serv.localClosed = true
				if serv.remoteClosed {
					serv.Close()
				} else {
					time.AfterFunc(time.Minute*3, func() { serv.Close() })
				}
			}
		// server events
		case ev := <-comm.Events:
			switch ev.Type {
			case session.SESSION:
				log.Fatal("local should not have received this type of event")
			case session.DATA:
				serv := ev.Session.Obj.(*Serv)
				serv.clientConn.Write(ev.Data)
			case session.SIGNAL:
				sig := ev.Data[0]
				if sig == sigClose {
					serv := ev.Session.Obj.(*Serv)
					time.AfterFunc(time.Second*3, func() {
						serv.clientConn.Close()
					})
					serv.remoteClosed = true
					if serv.localClosed {
						serv.Close()
					} else {
						time.AfterFunc(time.Minute*3, func() { serv.Close() })
					}
				} else if sig == sigPing {
				}
			case session.ERROR:
				log.Fatal("error when communicating with server ", string(ev.Data))
			}
		}
	}
}
Exemplo n.º 24
0
func run(projection bool) {
	var t []Point3D
	var p *Point3D

	tg.Clear(tg.ColorRed|tg.AttrBold, tg.ColorBlack|tg.AttrBold)

	angleX, angleY, angleZ := 0.0, 0.0, 0.0
	c := NewCanvas()
	for {
		//for rounds := 0; rounds < 1000; rounds++ {

		// Will hold transformed vertices.
		t = []Point3D{}

		for _, v := range vertices {
			// Rotate the point around X axis, then around Y axis, and finally around Z axis.
			p = &v
			p = p.RotateX(angleX)
			p = p.RotateY(angleY)
			p = p.RotateZ(angleZ)
			if projection {
				// Transform the point from 3D to 2D
				p = p.Project(50, 50, 50, 50)
			}
			// Put the point in the list of transformed vertices
			t = append(t, *p)
		}

		for _, f := range faces {
			c.DrawLine(t[f[0]].x, t[f[0]].y, t[f[1]].x, t[f[1]].y)
			c.DrawLine(t[f[1]].x, t[f[1]].y, t[f[2]].x, t[f[2]].y)
			c.DrawLine(t[f[2]].x, t[f[2]].y, t[f[3]].x, t[f[3]].y)
			c.DrawLine(t[f[3]].x, t[f[3]].y, t[f[0]].x, t[f[0]].y)
		}

		f := c.Frame(-40, -40, 80, 80)

		//stdscr.AddStr(0, 0, '{0}\n'.format(f))
		xoffset := 2
		for y, line := range strings.Split(f, "\n") {
			pos := 0
			for _, r := range line { // iterates over runes, not positions
				tg.SetCell(xoffset+pos, y, r, tg.ColorRed|tg.AttrBold, tg.ColorBlack|tg.AttrBold)
				pos++
			}
		}

		//stdscr.Refresh()
		tg.Flush()

		angleX += 2.0
		angleY += 3.0
		angleZ += 5.0

		time.Sleep(50 * time.Millisecond)

		c.Clear()

		//tg.Clear(tg.ColorRed|tg.AttrBold, tg.ColorBlack|tg.AttrBold)

		// TODO: Fork termbox and implement PeekEvent
		//e := PeekEvent()
		//switch e.Type {
		//case EventKey:
		//	switch e.Key {
		//	case KeyEsc, KeyEnter, KeySpace:
		//		return
		//	}
		//}
	}
}
Exemplo n.º 25
0
func termboxExample() {
	err := termbox.Init()
	if err != nil {
		panic(err)
	}
	defer termbox.Close()

	termbox.SetInputMode(termbox.InputEsc | termbox.InputMouse)

	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
	termbox.Flush()
	inputmode := 0
	ctrlxpressed := false
loop:
	for {
		switch ev := termbox.PollEvent(); ev.Type {
		case termbox.EventKey:

			// コンソールが消えるっぽい
			if ev.Key == termbox.KeyCtrlS && ctrlxpressed {
				termbox.Sync()
				break
			}

			// Ctrl+Xモード時のCtrl+Qでループを抜ける
			if ev.Key == termbox.KeyCtrlQ && ctrlxpressed {
				break loop
			}

			if ev.Key == termbox.KeyCtrlC && ctrlxpressed {
				chmap := []termbox.InputMode{
					termbox.InputEsc | termbox.InputMouse,
					termbox.InputAlt | termbox.InputMouse,
					termbox.InputEsc,
					termbox.InputAlt,
				}
				inputmode++
				if inputmode >= len(chmap) {
					inputmode = 0
				}
				termbox.SetInputMode(chmap[inputmode])
			}

			// Ctrl+X 入モード切り替え
			if ev.Key == termbox.KeyCtrlX {
				ctrlxpressed = true
			} else {
				ctrlxpressed = false
			}

			termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
			dispatch_press(&ev)
			pretty_print_press(&ev)
			termbox.Flush()
		case termbox.EventResize:
			// ターミナルのサイズ変更で呼ばれる
			termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
			pretty_print_resize(&ev)
			termbox.Flush()
		case termbox.EventMouse:
			// ターミナルにタッチすると呼ばれる
			termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
			pretty_print_mouse(&ev)
			termbox.Flush()
		case termbox.EventError:
			panic(ev.Err)
		}
	}
}
Exemplo n.º 26
0
func main() {
	tm.Init()
	tm.Clear(tm.ColorDefault, tm.ColorDefault)

	gameOver := false
	playerWon := false

	emitter := emission.NewEmitter()
	emitter.On(event.EVENT_KEY_CTRL_C, func() {
		gameOver = true
	})

	emitter.On(event.EVENT_PLAYER_WINS, func() {
		playerWon = true
		gameOver = true
	})

	emitter.On(event.EVENT_PLAYER_LOSES, func() {
		gameOver = true
	})

	keyboard := new(keyboard.Keyboard)
	keyboard.Init(emitter)

	mainboard := new(gameboard.Mainboard)
	mainboard.Init(1, 1, 50, 20)

	player := new(player.Player)
	player.Init(emitter, 1, 50, 20)

	alienManager := new(alien.AlienManager)
	alienManager.Init(emitter, 1, 1, 50, 20)

	var currentTime syscall.Timeval

	eventQueue := make(chan tm.Event)
	go func() {
		for {
			eventQueue <- tm.PollEvent()
		}
	}()

	timer := time.NewTimer(time.Duration(time.Millisecond * 60))

	for gameOver == false {
		select {
		case ev := <-eventQueue:
			if ev.Type == tm.EventKey {
				keyboard.HandleEvent(ev.Key)
			}
		case <-timer.C:
			syscall.Gettimeofday(&currentTime)

			emitter.Emit(event.EVENT_HEARTBEAT, (int64(currentTime.Sec)*1e3 + int64(currentTime.Usec)/1e3))
			timer.Reset(time.Duration(time.Millisecond * 60))
		}

		tm.Flush()
	}

	tm.Close()

	if playerWon == true {
		fmt.Println("You win!")
	} else {
		fmt.Println("You lose :(")
	}
}
Exemplo n.º 27
0
func Clear() {
	tm.Clear(tm.ColorDefault, toTmAttr(ThemeAttr("bg")))
}
Exemplo n.º 28
0
Arquivo: tor.go Projeto: kybin/tor
func main() {
	var newFlag bool
	flag.BoolVar(&newFlag, "new", false, "let tor to edit a new file.")
	flag.Parse()

	args := flag.Args()
	if len(args) == 0 {
		fmt.Println("please, set text file")
		os.Exit(1)
	}
	farg := args[len(args)-1]

	f, initL, initO, err := parseFileArg(farg)
	if err != nil {
		fmt.Println("file arg is invalid: ", err)
		os.Exit(1)
	}

	exist := true
	if _, err := os.Stat(f); os.IsNotExist(err) {
		exist = false
	}
	if !exist && !newFlag {
		fmt.Println("file not exist. please retry with -new flag.")
		os.Exit(1)
	} else if exist && newFlag {
		fmt.Println("file already exist.")
		os.Exit(1)
	}

	var text *Text
	if exist {
		text, err = open(f)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	} else {
		lines := make([]Line, 0)
		lines = append(lines, Line{""})
		text = &Text{lines: lines, tabToSpace: false, tabWidth: 4, edited: false}
	}

	err = term.Init()
	if err != nil {
		panic(err)
	}
	defer term.Close()
	term.SetInputMode(term.InputAlt)
	// term.SetOutputMode(term.Output256)
	term.Clear(term.ColorDefault, term.ColorDefault)
	term.Flush()

	termw, termh := term.Size()
	mainarea := NewArea(Point{0, 0}, Point{termh - 1, termw})
	win := NewWindow(mainarea.Size())
	cursor := &Cursor{}
	selection := &Selection{}
	history := newHistory()

	mode := &ModeSelector{}
	mode.normal = &NormalMode{
		text:      text,
		cursor:    cursor,
		selection: selection,
		history:   history,
		f:         f,
		mode:      mode,
		copied:    loadConfig("copy"),
	}
	mode.find = &FindMode{
		mode: mode,
		str:  loadConfig("find"),
	}
	mode.replace = &ReplaceMode{
		mode: mode,
		str:  loadConfig("replace"),
	}
	mode.gotoline = &GotoLineMode{
		cursor: cursor,
		mode:   mode,
	}
	mode.exit = &ExitMode{
		f:      f,
		cursor: cursor,
		mode:   mode,
	}
	mode.current = mode.normal // will start tor as normal mode.

	selection.m = mode.normal
	// Set cursor.
	cursor.m = mode.normal
	if initL != -1 {
		l := initL
		// to internal line number
		if l != 0 {
			l--
		}
		cursor.GotoLine(l)
		if initO != -1 {
			cursor.SetO(initO)
		}
	} else {
		l, b := loadLastPosition(f)
		cursor.GotoLine(l)
		cursor.SetCloseToB(b)
	}

	events := make(chan term.Event, 20)
	go func() {
		for {
			events <- term.PollEvent()
		}
	}()
	for {
		win.Follow(cursor, 3)
		clearScreen(mainarea)
		drawScreen(mainarea, win, mode.normal.text, selection, cursor)
		if mode.current.Error() != "" {
			printErrorStatus(mode.current.Error())
		} else {
			printStatus(mode.current.Status())
		}
		if mode.current == mode.normal {
			winP := cursor.Position().Sub(win.min)
			term.SetCursor(mainarea.min.o+winP.o, mainarea.min.l+winP.l)
		} else {
			term.SetCursor(vlen(mode.current.Status(), mode.normal.text.tabWidth), termh)
		}
		term.Flush()

		// wait for keyboard input
		select {
		case ev := <-events:
			switch ev.Type {
			case term.EventKey:
				mode.current.Handle(ev)
			case term.EventResize:
				term.Clear(term.ColorDefault, term.ColorDefault)
				termw, termh = term.Size()
				resizeScreen(mainarea, win, termw, termh)
			}
		}
	}
}
Exemplo n.º 29
0
func (tb termbox) Clear() {
	T.Clear(T.ColorWhite, T.ColorBlack)
}
Exemplo n.º 30
0
func (tb termboxImpl) Clear() {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
}