สอนสร้างเกมส์บริหารเหตุการณ์ต่างๆในร้านนวด

ตัวอย่างสุ่มเหตุการณ์ต่างๆในร้านนวด ที่เหลือต่อยอดเอาเองนะครับ ^^

ในบทความนี้ เราจะสร้างระบบบริหารร้านนวดโดยใช้ Spring Boot ซึ่งมีฟีเจอร์ต่างๆ เช่น:

  • สุ่ม Event ที่ส่งผลกระทบต่อ Entity
  • แจ้งสถานะผลกระทบผ่าน WebSocket
  • อัปเดตข้อมูลในฐานข้อมูลโดยตรง

1. WebSocket Configuration

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/event-websocket").setAllowedOrigins("*").withSockJS();
    }
}
    

2. Event Entity

@Entity
public class Event {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String type;
    private String description;
    private double impact;
    private String affectedEntity;
    private Long affectedId;

    // Getters and Setters
}
    

3. Event Service

@Service
public class EventService {
    private final Random random = new Random();
    private final SimpMessagingTemplate messagingTemplate;
    private final RoomRepository roomRepository;
    private final MassageTherapistRepository therapistRepository;
    private final CustomerRepository customerRepository;

    public EventService(SimpMessagingTemplate messagingTemplate,
                        RoomRepository roomRepository,
                        MassageTherapistRepository therapistRepository,
                        CustomerRepository customerRepository) {
        this.messagingTemplate = messagingTemplate;
        this.roomRepository = roomRepository;
        this.therapistRepository = therapistRepository;
        this.customerRepository = customerRepository;
    }

    @Scheduled(fixedRate = 10000) // สุ่มทุก 10 วินาที
    public void generateRandomEvent() {
        Event event = new Event();
        String affectedEntity = randomAffectedEntity();
        Long affectedId = applyImpactToEntity(affectedEntity);

        event.setType(randomEventType());
        event.setDescription(randomEventDescription(event.getType(), affectedEntity));
        event.setImpact(randomImpactValue());
        event.setAffectedEntity(affectedEntity);
        event.setAffectedId(affectedId);

        // ส่ง Event ไปยัง WebSocket
        messagingTemplate.convertAndSend("/topic/events", event);
    }

    private String randomAffectedEntity() {
        String[] entities = {"Room", "MassageTherapist", "Customer"};
        return entities[random.nextInt(entities.length)];
    }

    private String randomEventDescription(String type, String entity) {
        switch (type) {
            case "Positive": return entity + " ได้รับผลกระทบเชิงบวก!";
            case "Negative": return entity + " ได้รับผลกระทบเชิงลบ!";
            default: return "ไม่มีผลกระทบที่ชัดเจน.";
        }
    }

    private double randomImpactValue() {
        return random.nextDouble() * 100 - 50; // ค่าผลกระทบระหว่าง -50 ถึง 50
    }

    private Long applyImpactToEntity(String entity) {
        switch (entity) {
            case "Room":
                return applyImpactToRoom();
            case "MassageTherapist":
                return applyImpactToTherapist();
            case "Customer":
                return applyImpactToCustomer();
            default:
                return null;
        }
    }

    private Long applyImpactToRoom() {
        List<Room> rooms = roomRepository.findAll();
        if (rooms.isEmpty()) return null;

        Room room = rooms.get(random.nextInt(rooms.size()));
        room.setCapacity(room.getCapacity() + random.nextInt(5) - 2); // เพิ่ม/ลดความจุ
        roomRepository.save(room);
        return room.getId();
    }

    private Long applyImpactToTherapist() {
        List<MassageTherapist> therapists = therapistRepository.findAll();
        if (therapists.isEmpty()) return null;

        MassageTherapist therapist = therapists.get(random.nextInt(therapists.size()));
        therapist.setSkillLevel(Math.max(0, therapist.getSkillLevel() + random.nextInt(3) - 1)); // เพิ่ม/ลดทักษะ
        therapistRepository.save(therapist);
        return therapist.getId();
    }

    private Long applyImpactToCustomer() {
        List<Customer> customers = customerRepository.findAll();
        if (customers.isEmpty()) return null;

        Customer customer = customers.get(random.nextInt(customers.size()));
        customer.setSatisfaction(Math.max(0, customer.getSatisfaction() + random.nextDouble() * 10 - 5)); // เพิ่ม/ลดความพึงพอใจ
        customerRepository.save(customer);
        return customer.getId();
    }
}
    

4. Frontend Integration

<script src="https://cdn.jsdelivr.net/npm/sockjs-client"></script>
<script src="https://cdn.jsdelivr.net/npm/stompjs"></script>
<script>
    const socket = new SockJS('/event-websocket');
    const stompClient = Stomp.over(socket);

    stompClient.connect({}, () => {
        stompClient.subscribe('/topic/events', (message) => {
            const event = JSON.parse(message.body);
            console.log("Received event:", event);
            alert(`Event: ${event.description}, Impact: ${event.impact}`);
        });
    });
</script>
    

ถ้าต้องการปรับแต่งเพิ่มเติม สามารถดูรายละเอียดในโค้ดต้นฉบับได้ครับ!

ความคิดเห็น

บทความที่ได้รับความนิยม