In swarm robotics systems, coordinated behaviors emerge via local interactions among the robots as well as between robots and the environment. For a swarm of robots performing a set of pre-defined tasks in an enclosed region, this paper develops a decentralized mechanism to allocate tasks to each robot by leveraging the spatial interactions occurring among the robots as they move around the domain. With the aim of achieving a desired percentage of the swarm performing each task, the developed strategy allows individual robots to switch between different tasks with a certain probability when they encounter other robots in the region. We develop an analytical model to describe the inter-robot encounters occurring in a densely packed swarm of robots using ideas from the Enskog theory of dense gases and illustrate how the swarm can leverage this model to achieve the desired allocation levels. Furthermore, the inter-robot encounters enable the robots to measure the current allocation of the swarm, which is then used to regulate the rate at which they switch between tasks. This allows the swarm to speed up or slow down the rate of transitions between tasks depending on how far the current allocation is from the desired values, ultimately facilitating uninterrupted task execution by the robots. The methods introduced in this paper illustrate how naturally occurring encounters among robots in a swarm can be used to allocate tasks to the robots in a closed-loop manner. The developed algorithm is completely decentralized and can be deployed on minimalistic robots without the need for communication or a central coordinator. The performance of the algorithm is demonstrated on a swarm of real robots.