Пример #1
0
// Update display callback. Receives mail check result with new messages count
// and polling error status.
//
// Update checked time and, if needed, send info or error to renderer and user
// alerts.
//
func (app *AppletGmail) updateDisplay(delta int, e error) {
	eventTime := time.Now().String()[11:19]
	label := "Checked: " + eventTime
	switch {
	case e != nil:
		label = "Update Error: " + eventTime + "\n" + e.Error() // Error time is refreshed.
		log.Err(e, "Check mail")
		if app.err == nil || e.Error() != app.err.Error() { // Error buffer, dont warn twice the same information.
			app.render.Error(e)
			app.PopUp("Mail check error", e.Error())
			app.err = e
		}

	case delta > 0:
		log.Debug("  * Count changed", delta)
		app.sendAlert(delta)

	case delta == 0:
		log.Debug("", " * no change")
	}

	switch {
	case e == nil && app.err != nil: // Error disapeared. Cleaning buffer and refresh display.
		app.render.Set(app.data.Count())
		app.err = nil

	case delta != 0: // Refresh display only if changed.
		app.render.Set(app.data.Count())
	}
	app.SetLabel(label)
}
Пример #2
0
// Get mails from server.
//
func (feed *Feed) get() error {
	log.Debug("Get mails from server")

	// Prepare request with header
	request, e := http.NewRequest("GET", feedGmail, nil)
	if e != nil {
		return e
	}
	request.Header.Add("Authorization", "Basic "+feed.login)

	// Try to get data from source.
	response, e2 := new(http.Client).Do(request)
	if e2 != nil {
		return e2
	}
	defer response.Body.Close()

	body, e3 := ioutil.ReadAll(response.Body)
	if e3 != nil {
		return e3
	}

	// Parse data.
	if e := xml.Unmarshal(body, feed); e != nil {
		return e
	}
	return nil
}
Пример #3
0
func (t *TicTacToeAI) PrintBoard() {
	for i := 0; i < 3; i++ {
		a := t.board[i][0]
		b := t.board[i][1]
		c := t.board[i][2]

		log.Debug(a + b + c)
	}
}
Пример #4
0
func (h *GameHub) Run() {
	log.SetPrefix("GameHub")
	log.SetDebug(true)
	log.Info("Started GameHub")

	h.createDemoRooms()

	//InitTest()
	h.TestQuiz()

	for {
		select {

		// Player entered lobby.
		case p := <-h.register:
			h.players[p.id] = p
			h.connections[p.conn] = true
			h.lobby.addPlayer(p)
			log.Debug("Added Player " + p.id)

		// Player exited website.
		case p := <-h.unregister:
			delete(h.players, p.id)
			delete(h.connections, p.conn)
			close(p.conn.send)
			log.Debug("Player " + p.id + " exited")

		// Distribute broadcast messages to all connections.
		case m := <-h.broadcast:
			if h.handleMessage(m) != true {
				for c := range h.connections {
					select {
					case c.send <- m:
					default:
						delete(h.connections, c)
						close(c.send)
						go c.ws.Close()
					}
				}
			}
		}
	}
}
Пример #5
0
// StartApplet will prepare and launch a cairo-dock applet. If you have provided
// events, they will respond when needed, and you have nothing more to worry
// about your applet management. One optional poller can be provided atm.
//
// List of the steps, and their effect:
//   * Load applet events definition = DefineEvents().
//   * Connect the applet to cairo-dock with DBus. This also activate events callbacks.
//   * Initialise applet with option load config activated = Init(true).
//   * Start and run the polling loop if needed. This start a instant check, and
//     manage regular and manual timer refresh.
//   * Wait for the dock End signal to close the applet.
//
func StartApplet(cda *CDApplet, app AppletInstance, poller ...*poller.Poller) {
	log.Debug("Applet started")
	defer log.Debug("Applet stopped")

	// Define and connect events to the dock
	cda.Events.Reload = func(loadConf bool) {
		app.Reload(loadConf)
	}

	app.DefineEvents()
	cda.ConnectToBus()

	// Load config and apply user settings.
	app.Init(true)

	// Prepare signals channels.
	close := cda.GetCloseChan()

	if len(poller) == 0 {
		<-close // Just wait for End event signal.

	} else { // With only one poller currently managed.

		restart := poller[0].GetRestart() // Restart chan for user events.

		for { // Start main loop and handle events until the End signal is received from the dock.

			// Start a timer if needed. The poller will do the first check right now.
			tick := poller[0].Start()

			select { // Wait for events. Until the End signal is received from the dock.
			case <-close: // Received End event. That's all folks.
				return

			case <-tick.C: // End of timer. Reset timer.

			case <-restart: // Rechecked manually. Reset timer.
			}
		}
	}
}
Пример #6
0
func (quiz *QuizBowlGame) Score(msg string, player *Player) {
	if player.data == nil {
		player.data = 0
	}

	var answer QuizBowlAnswer
	err := rjson.Unmarshal([]byte(msg), &answer)
	if err != nil {
		fmt.Println(err)
		log.Debug("Could not score answer")
	}

	var m string
	question := quiz.findQuestionById(answer.QuestionId)
	correctAnswer := question.CorrectAnswer
	answerText := quiz.findAnswerText(question, correctAnswer)
	fmt.Println(answerText)
	fmt.Println(correctAnswer, answer.AnswerId)
	if answer.AnswerId == correctAnswer {
		player.data = player.data.(int) + 200
		fmt.Println("Score:", player.data)
		m = "Correct Answer! \nCurrent Score: " + strconv.Itoa(player.data.(int))
	} else {
		m = "Wrong! The correct answer is " + answerText + "\n Current score: " + strconv.Itoa(player.data.(int))
	}

	msg2 := Message{
		Operation: "SendResult",
		Sender:    "Server",
		RoomID:    "",
		Message:   m,
	}

	b, err2 := rjson.Marshal(msg2)
	if err2 != nil {
		log.Debug("There was a marshalling error.")
		return
	}
	//Send message back to player
	player.conn.send <- string(b)
}
Пример #7
0
// callback for poller mail checking. Launch the check mail action.
// Check for new mails. Return the mails count delta (change since last check).
//
func (feed *Feed) Check() {
	log.Debug("Check mails")
	if !feed.IsValid() {
		feed.callResult(0, errors.New("No account informations provided."))
		return
	}

	count := feed.Count() // save current count.
	feed.Clear()          // reset list.
	e := feed.get()       // Get new data.
	feed.callResult(feed.Count()-count, e)
}
Пример #8
0
func (quiz *QuizBowlGame) loadQuestions() {
	bs, err := ioutil.ReadFile("json/sample-questions.json")
	if err != nil {
		return
	}

	questions := make([]Question, 0)

	err = rjson.Unmarshal(bs, &questions)
	if err != nil {
		fmt.Println("Error Loading Questions:", err)
	}
	log.Debug("Loaded questions")

	quiz.questions = questions
}
Пример #9
0
func (h *GameHub) handleMessage(msg string) bool {
	var conn *connection
	var player *Player
	var handledMessage bool

	var data Message
	err := rjson.Unmarshal([]byte(msg), &data)
	if err != nil {
		fmt.Println("error:", err)
	}

	log.Debug(msg)

	// Get sender's connection
	sender := data.Sender
	if sender != "" && sender != "Server" {
		player = h.players[sender]
		conn = player.conn
	}

	switch data.Operation {
	case "CreateRoom":
		fmt.Println("CreateRoom")
		r := &GameRoom{players: make(map[string]bool)}
		r.roomId = uniuri.New()
		h.rooms[r.roomId] = r
		fmt.Println(h.getRoomList())

	// message to say room was created
	// move player to room
	case "ChangeNick":
		msg := player.ChangeNick(data.Message)
		h.sendBroadcastMessage(msg, "Lobby")
		// Send message to room saying nick has changed
		handledMessage = true
	case "JoinRoom":
		fmt.Println("JoinRoom")
		// TODO: Check if player is already in game room
		// Store gameroom data also in player object?
		roomId := data.Message
		room, err := h.rooms[roomId]
		if err != false {
			room.addPlayer(player)
			log.Debug("Player " + player.id + " added to room " + roomId)
			fmt.Println(room.players)
		}
	case "LeaveRoom":
		fmt.Println("LeaveRoom")
		// TODO: Verify player is already in game room
		roomId := data.Message
		room, err := h.rooms[roomId]
		if err != false {
			room.removePlayer(player)
			log.Debug("Player " + player.id + " left room " + roomId)
			fmt.Println(room.players)
		}

	case "StartGame":
		roomId := data.RoomID
		room := h.rooms[roomId]
		room.game.startGame(room, h)
	case "GetGameTypes":
		conn.send <- h.getGameTypes()
		handledMessage = true
	case "GetPlayerList":
		for _, v := range h.players {
			fmt.Println(v)
		}
	case "GetRoomList":
		conn.send <- h.getRoomList()
		handledMessage = true
	default:
		// Send to specific room for handling
		room := h.findRoomById(data.RoomID)
		if room != nil {
			fmt.Println(room)
			if room.game != nil {
				room.game.HandleGameMessage(msg, h)
			}
		}
	}

	fmt.Println(data.Message)
	return handledMessage
}
Пример #10
0
// Reset all settings and restart timer.
//
func (app *AppletGmail) Reload(confChanged bool) {
	log.Debug("Reload module")
	app.Init(confChanged)
	app.Actions.Launch(ActionCheckMail) // CheckMail recheck and reset the timer.
}