Here's a step-by-step guide to creating a peer-to-peer quiz game in Godot 4.4 where two players take turns hosting questions and answering. The game will follow your requirements:
Project Structure
-
Scenes:
MainScene.gd: Handles server/client setup.
GameScene.gd: Manages gameplay (questions, answers, results).
- UI elements (Labels, Buttons, etc.).
-
Networking Components:
MultiplayerAPI for P2P communication.
MultiplayerPeerUDPPeer for UDP networking.
Step 1: Create the Main Scene (Server/Client Setup)
MainScene.gd
extends Node
# UI Elements
onready var host_button = $HostButton
onready var join_button = $JoinButton
onready var ip_input = $IPInput
onready var status_label = $StatusLabel
# Networking
var multiplayer: MultiplayerAPI
var peer: MultiplayerPeerUDPPeer
func _ready():
# Initialize Multiplayer API
multiplayer = get_tree().multiplayer_api
peer = MultiplayerPeerUDPPeer.new()
multiplayer.set_server(peer)
# Connect signals
host_button.connect("pressed", self, "_on_host_pressed")
join_button.connect("pressed", self, "_on_join_pressed")
func _on_host_pressed():
# Host as Server
peer.listen(4242) # Port 4242
status_label.text = "Hosting... IP: " + get_ip_address()
get_tree().change_scene_to("res://GameScene.tscn")
func _on_join_pressed():
# Join as Client
var ip = ip_input.text
if peer.connect_to_host(ip, 4242):
status_label.text = "Connected to " + ip
get_tree().change_scene_to("res://GameScene.tscn")
else:
status_label.text = "Connection failed!"
func get_ip_address() -> String:
# Get local IP for hosting
var addresses = OS.get_internet_addresses()
for address in addresses:
if address.begins_with("192."): # Filter local IPs
return address
return "127.0.0.1" # Fallback
Step 2: Create the Game Scene (Quiz Logic)
GameScene.gd
extends Node
# UI Elements
onready var question_label = $QuestionLabel
onready var option_buttons = $OptionContainer.get_children()
onready var answer_input = $AnswerInput
onready var submit_button = $SubmitButton
onready var result_label = $ResultLabel
onready var continue_button = $ContinueButton
# Game State
var is_host = false
var current_question = 0
var round = 1
var scores = [0, 0] # [Player 1 (Host), Player 2]
var questions = [ # Example questions (replace with your data)
{"question": "What is 2+2?", "options": ["3", "4", "5", "6"], "answer": "4"},
{"question": "Capital of France?", "options": ["London", "Paris", "Berlin", "Madrid"], "answer": "Paris"},
{"question": "What is the largest planet?", "options": ["Mars", "Jupiter", "Earth", "Venus"], "answer": "Jupiter"}
]
# Networking
var multiplayer: MultiplayerAPI
var peer_id: int # Player ID (0 is host, 1 is client)
func _ready():
multiplayer = get_tree().multiplayer_api
peer_id = multiplayer.get_unique_id()
is_host = (peer_id == 0)
# Initialize game
_start_new_round()
# Connect signals
submit_button.connect("pressed", self, "_on_answer_submitted")
func _start_new_round():
current_question = 0
round += 1
result_label.text = ""
continue_button.visible = false
# Host starts first
if is_host:
_send_question()
else:
# Wait for host's first question
pass
func _send_question():
if current_question < 3:
# Get next question
var question = questions[current_question]
@rpc("all") func send_question(q: Dictionary):
if is_host:
question_label.text = q.question
for i in 0 to 3:
option_buttons[i].text = q.options[i]
answer_input.text = "" # Clear input
current_question += 1
else:
_show_results()
func _on_answer_submitted():
var answer = answer_input.text
@rpc("all") func send_answer(a: String):
if not is_host:
# Client sends answer to host
pass # Handled by the host
answer_input.text = ""
submit_button.disabled = true
# Host checks the answer
if is_host:
_check_answer(answer)
func _check_answer(given_answer: String):
var correct_answer = questions[current_question - 1]["answer"]
if given_answer == correct_answer:
scores[peer_id] += 1
result_label.text = "Correct!"
else:
result_label.text = "Incorrect!"
# Proceed to next question
if peer_id == 0: # Host controls flow
_send_question()
func _show_results():
result_label.text = "Round " + str(round) + " Results:\n"
result_label.text += "Player 1: " + str(scores[0]) + "\n"
result_label.text += "Player 2: " + str(scores[1]) + "\n"
continue_button.visible = true
continue_button.text = "Continue?"
# Wait for both players to agree to continue
@rpc("all") func request_continue():
pass # Triggers UI for both players
func _on_continue_pressed():
if is_host:
# Both players must agree (simplified for example)
@rpc("all") func start_next_round():
_start_new_round()
else:
# Client confirms
pass # Host handles logic
# Handle RPC calls
@rpc("all") func handle_answer(answer: String):
if is_host:
_check_answer(answer)
Step 3: UI Setup (GameScene.tscn)
- Node Structure:
QuestionLabel (Label): Displays the current question.
OptionContainer (HBoxContainer/FlowContainer) with 4 Button nodes for options.
AnswerInput (LineEdit): For typing answers.
SubmitButton (Button): To submit answers.
ResultLabel (Label): Shows results after each question.
ContinueButton (Button): To proceed to the next round.
Step 4: Networking Logic
- Host (Player 1):
- Starts the server and initiates the first question.
- Acts as the authority for game state (scores, turn order).
- Client (Player 2):
- Connects to the host’s IP.
- Receives questions and sends answers via RPC.
Step 5: Running the Game
- Player 1:
- Hosts the game by pressing the "Host" button.
- The scene switches to
GameScene, and the host sends the first question.
- Player 2:
- Joins by entering Player 1’s IP and pressing "Join".
- Receives the first question and answers.
- Game Flow:
- After each question, the host checks the answer and updates scores.
- After 3 questions from each player, results are displayed.
- Both players can choose to continue to the next round.
Key Concepts
-
RPC (Remote Procedure Calls):
@rpc("all") sends data to all peers.
- Host controls the game flow via RPCs.
-
Peer IDs:
peer_id == 0 is the host.
peer_id == 1 is the client.
-
State Management:
- Scores and rounds are tracked by the host.
- The host enforces turn order and question progression.
Improvements
- UI Enhancements: Add animations, better question display.
- Error Handling: Disconnect detection, reconnect logic.
- Question Bank: Load questions from a file or database.
- Security: Use
WebSocket or TLS/SSL for production.
Would you like help with any specific part of the implementation?