The study aimed to develop and validate a gamified cognitive flexibility task through brain imaging, and to investigate behavioral and brain activation differences between young and older adults during task performance. Thirty-one young adults (aged 18-35) and 31 older adults (aged 60-80) were included in the present study. All participants underwent fMRI scans while completing the gamified cognitive flexibility task. Results showed that young adults outperformed older adults on the task. The left inferior frontal junction (IFJ), a key region of cognitive flexibility, was significantly activated during the task in both older and young adults. Comparatively, the percent signal change in the left IFJ was stronger in older adults than in young adults. Moreover, older adults demonstrated more precise representations during the task in the left IFJ. Additionally, the left inferior parietal lobule (IPL) and superior parietal lobule in older adults and the left middle frontal gyrus (MFG) and inferior frontal gyrus in young adults were also activated during the task. Psychophysiological interaction analyses showed significant functional connectivity between the left IFJ and the left IPL, as well as the right precuneus in older adults. In young adults, significant functional connectivity was found between the left IFJ and the left MFG, as well as the right angular. The current study provides preliminary evidence for the validity of the gamified cognitive flexibility task through brain imaging. The findings suggest that this task could serve as a reliable tool for assessing cognitive flexibility and for exploring age-related differences of cognitive flexibility in both brain and behavior.