-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomNameWinner.sol
49 lines (39 loc) · 1.8 KB
/
RandomNameWinner.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract RandomNameWinner {
string[] private namePool = ["Alice", "Bob", "Charlie", "David", "Eve"];
mapping(address => string) public participants;
address[] private participantAddresses;
address public owner;
string public winnerName;
address public winnerAddress;
constructor() {
owner = msg.sender;
}
// Join the game and get a random name
function joinGame() public {
require(bytes(participants[msg.sender]).length == 0, "You have already joined!");
// Generate random index for name
uint randomIndex = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender, participantAddresses.length))) % namePool.length;
string memory assignedName = namePool[randomIndex];
participants[msg.sender] = assignedName;
participantAddresses.push(msg.sender);
}
// Pick a winner (only owner can call this)
function pickWinner() public {
require(msg.sender == owner, "Only the owner can pick the winner");
require(participantAddresses.length > 0, "No participants to pick a winner");
uint randomIndex = uint(keccak256(abi.encodePacked(block.timestamp, block.difficulty, participantAddresses.length))) % participantAddresses.length;
winnerAddress = participantAddresses[randomIndex];
winnerName = participants[winnerAddress];
}
// Get participant's assigned name
function getMyName() public view returns (string memory) {
require(bytes(participants[msg.sender]).length > 0, "You have not joined the game");
return participants[msg.sender];
}
// Get total participants count
function getTotalParticipants() public view returns (uint) {
return participantAddresses.length;
}
}