Certainly! I can help you create a simple idle game in Go that runs as a web server, uses a database to store player data, and displays a public leaderboard—all contained within a single Go script. We'll use SQLite for the database since it can be embedded and doesn't require a separate server.
Overview:
- Language: Go
- Database: SQLite (embedded)
- Web Server: Built using Go's
net/http package
- Game Concept: Let's create a simple idle game where players accumulate gold over time. They can also click a button to earn more gold actively.
- Leaderboard: Displays top players based on total gold.
Step-by-Step Guide
1. Set Up the Go Environment
Make sure you have Go installed on your Windows machine. If not, download it from the official website.
2. Create a Single Go Script
Create a new file named idle_game.go in any folder.
3. Import Necessary Packages
We'll need the following packages:
net/http for the web server
html/template to render HTML pages
database/sql and _ "github.com/mattn/go-sqlite3" for the database
sync for concurrency control
4. Write the Code
Below is the complete code for the game:
package main
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
"html/template"
"log"
"net/http"
"strconv"
"sync"
"time"
)
// Player represents a game player
type Player struct {
Name string
Gold int
LastTime time.Time
}
var (
db *sql.DB
tmpl *template.Template
mu sync.Mutex
)
func main() {
var err error
db, err = sql.Open("sqlite3", "./idle_game.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
createTable()
tmpl = template.Must(template.New("index").Parse(htmlTemplate))
http.HandleFunc("/", indexHandler)
http.HandleFunc("/click", clickHandler)
http.HandleFunc("/leaderboard", leaderboardHandler)
log.Println("Starting server on :8080")
http.ListenAndServe(":8080", nil)
}
func createTable() {
sqlStmt := `
CREATE TABLE IF NOT EXISTS players (
name TEXT PRIMARY KEY,
gold INTEGER,
last_time DATETIME
);
`
_, err := db.Exec(sqlStmt)
if err != nil {
log.Fatalf("%q: %s\n", err, sqlStmt)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
http.Redirect(w, r, "/?name=Player"+strconv.Itoa(int(time.Now().Unix()%1000)), http.StatusSeeOther)
return
}
mu.Lock()
player := getPlayer(name)
updateGold(&player)
savePlayer(player)
mu.Unlock()
tmpl.Execute(w, player)
}
func clickHandler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
mu.Lock()
player := getPlayer(name)
updateGold(&player)
player.Gold += 10 // Add gold on click
savePlayer(player)
mu.Unlock()
http.Redirect(w, r, "/?name="+name, http.StatusSeeOther)
}
func leaderboardHandler(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query("SELECT name, gold FROM players ORDER BY gold DESC LIMIT 10")
if err != nil {
http.Error(w, err.Error(), 500)
return
}
defer rows.Close()
type LeaderboardEntry struct {
Name string
Gold int
}
var leaderboard []LeaderboardEntry
for rows.Next() {
var entry LeaderboardEntry
err = rows.Scan(&entry.Name, &entry.Gold)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
leaderboard = append(leaderboard, entry)
}
tmplLeaderboard.Execute(w, leaderboard)
}
func getPlayer(name string) Player {
var player Player
err := db.QueryRow("SELECT name, gold, last_time FROM players WHERE name = ?", name).Scan(&player.Name, &player.Gold, &player.LastTime)
if err == sql.ErrNoRows {
player = Player{Name: name, Gold: 0, LastTime: time.Now()}
savePlayer(player)
} else if err != nil {
log.Println(err)
}
return player
}
func updateGold(player *Player) {
now := time.Now()
duration := now.Sub(player.LastTime)
earned := int(duration.Seconds()) // Earn 1 gold per second
player.Gold += earned
player.LastTime = now
}
func savePlayer(player Player) {
_, err := db.Exec("REPLACE INTO players (name, gold, last_time) VALUES (?, ?, ?)", player.Name, player.Gold, player.LastTime)
if err != nil {
log.Println(err)
}
}
var htmlTemplate = `
<!DOCTYPE html>
<html>
<head>
<title>Idle Game</title>
</head>
<body>
<h1>Welcome, {{.Name}}</h1>
<p>You have {{.Gold}} gold.</p>
<form action="/click">
<input type="hidden" name="name" value="{{.Name}}">
<button type="submit">Earn Gold Actively</button>
</form>
<p><a href="/leaderboard">View Leaderboard</a></p>
</body>
</html>
`
var tmplLeaderboard = template.Must(template.New("leaderboard").Parse(`
<!DOCTYPE html>
<html>
<head>
<title>Leaderboard</title>
</head>
<body>
<h1>Leaderboard</h1>
<table>
<tr><th>Rank</th><th>Name</th><th>Gold</th></tr>
{{range $index, $element := .}}
<tr>
<td>{{$index | addOne}}</td>
<td>{{$element.Name}}</td>
<td>{{$element.Gold}}</td>
</tr>
{{end}}
</table>
<p><a href="/">Back to Game</a></p>
</body>
</html>
`))
func init() {
// Template function to add one to index (since range indexes start at 0)
tmplLeaderboard.Funcs(template.FuncMap{
"addOne": func(i int) int { return i + 1 },
})
}
5. Explanation of the Code
- Main Function: Sets up the database and starts the HTTP server on port
8080.
- Handlers:
/ (indexHandler): Main game page where the player can see their gold.
/click (clickHandler): Increments gold when the player clicks the button.
/leaderboard (leaderboardHandler): Displays the top players.
- Templates: Inline HTML templates render the game page and leaderboard.
- Database Functions:
createTable: Creates the players table if it doesn't exist.
getPlayer: Retrieves player data from the database.
updateGold: Calculates gold earned based on time elapsed.
savePlayer: Saves player data to the database.
- Concurrency Control:
sync.Mutex is used to prevent race conditions.
6. Run the Script
Open a command prompt, navigate to the folder containing idle_game.go, and run:
go run idle_game.go
7. Access the Game
- Open a web browser and navigate to
http://localhost:8080/.
- If you want to test with a specific name, use
http://localhost:8080/?name=YourName.
- Click the "Earn Gold Actively" button to gain gold manually.
- Gold accumulates over time automatically.
8. View the Leaderboard
- Visit
http://localhost:8080/leaderboard to see the top players.
9. Make the Game Accessible from the Internet
To allow connections from the internet:
- Port Forwarding: Configure your router to forward port
8080 to your machine.
- Firewall: Ensure that Windows Firewall allows inbound connections on port
8080.
- Static IP or Dynamic DNS: If your public IP changes, consider using a dynamic DNS service.
Notes
-
Single File: The entire game is contained within idle_game.go. The database idle_game.db will be created automatically in the same directory.
-
Cross-Platform: While you mentioned Windows, this Go script can run on any platform where Go is installed.
-
Dependencies: The only external dependency is the SQLite driver. Ensure you run go get to install it:
go get github.com/mattn/go-sqlite3
-
Security: This is a basic implementation for educational purposes. For a real-world application, consider adding user authentication and input validation.
Feel free to customize the game logic, templates, and features to better suit your vision. Let me know if you need further assistance or have questions about expanding the game!