当前位置:网站首页>[pyGame] stir up your brain and play the "24 o'clock" idea together ~ (awesome)
[pyGame] stir up your brain and play the "24 o'clock" idea together ~ (awesome)
2022-06-10 23:59:00 【Programmer pear】
Preface
author :“ Programmer pear ”
** The article brief introduction **: This article is mainly about the use of Pygame I wrote the little game of beating the hamster ~
** The source code of the article is available for free : In order to thank everyone who pays attention to me, the project source code of each article is none
Compensation sharing drop
Welcome friends give the thumbs-up 、 Collection 、 Leaving a message.
Small make up has words ——
hello ! Daily game update series —— Pear classmate Here we go again ! Today we are talking about a game that everyone is familiar with !
I played for the first time 24 When I was in junior high school , At that time, I played with my cousin at my cousin's house , My cousin offered to play 24 Click game , My cousin is better than me
They are three years younger , Maybe I'm in primary school .
Take out a deck of playing cards and remove the size monsters and cards , Pick four cards from the rest , Who can use addition, subtraction, multiplication and division to calculate 24 Even if the
win .
If everyone agrees to give up or someone calculates it, start a new game . The result is that our three brothers lose more and win less , Cousin Xian
However, it has been prepared .


Actually 24 Some small games can be used to play with friends when you are bored , It can also exercise thinking ability , Especially the little ones at home
Children improve their math skills ,
It's good to exercise more , Especially those children who are not good at math —— It can improve the speed and accuracy of mental arithmetic , When mathematics becomes
After the game, children are more interested ~ I'll show you today Write an interface “24 A little game ” Oh

Text

Introduction to the game :
(1) What is? 24 Click game ?
Chess and card puzzle games , The result is required to be equal to 24
(2) The rules of the game .
Arbitrary extraction 4 A digital (1——10), Add with 、 reduce 、 ride 、 except ( Parenthesized ) Count the number as 24. Each number must be used once and only once .“ count 24 spot ” As an intellectual game to exercise thinking , Attention should also be paid to the skills in calculation . When calculating , We can't put the... On the card 4 Different combinations of numbers —— To try , And you can't touch it indiscriminately .
example :3、8、8、9
answer :3×8÷(9-8)=24

( One ) Define the code of this part of the game game.py file .
'''
Define the game
'''
import copy
import random
import pygame
'''
Function:
Card class
Initial Args:
--x,y: Top left coordinates
--width: wide
--height: high
--text: Text
--font: [ The font path , font size ]
--font_colors(list): The font color
--bg_colors(list): Background color
'''
class Card(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, text, font, font_colors, bg_colors, attribute, **kwargs):
pygame.sprite.Sprite.__init__(self)
self.rect = pygame.Rect(x, y, width, height)
self.text = text
self.attribute = attribute
self.font_info = font
self.font = pygame.font.Font(font[0], font[1])
self.font_colors = font_colors
self.is_selected = False
self.select_order = None
self.bg_colors = bg_colors
''' Draw it on the screen '''
def draw(self, screen, mouse_pos):
pygame.draw.rect(screen, self.bg_colors[1], self.rect, 0)
if self.rect.collidepoint(mouse_pos):
pygame.draw.rect(screen, self.bg_colors[0], self.rect, 0)
font_color = self.font_colors[self.is_selected]
text_render = self.font.render(self.text, True, font_color)
font_size = self.font.size(self.text)
screen.blit(text_render, (self.rect.x+(self.rect.width-font_size[0])/2, self.rect.y+(self.rect.height-font_size[1])/2))
''' Button class '''
class Button(Card):
def __init__(self, x, y, width, height, text, font, font_colors, bg_colors, attribute, **kwargs):
Card.__init__(self, x, y, width, height, text, font, font_colors, bg_colors, attribute)
''' according to button function Perform the response operation '''
def do(self, game24_gen, func, sprites_group, objs):
if self.attribute == 'NEXT':
for obj in objs:
obj.font = pygame.font.Font(obj.font_info[0], obj.font_info[1])
obj.text = obj.attribute
self.font = pygame.font.Font(self.font_info[0], self.font_info[1])
self.text = self.attribute
game24_gen.generate()
sprites_group = func(game24_gen.numbers_now)
elif self.attribute == 'RESET':
for obj in objs:
obj.font = pygame.font.Font(obj.font_info[0], obj.font_info[1])
obj.text = obj.attribute
game24_gen.numbers_now = game24_gen.numbers_ori
game24_gen.answers_idx = 0
sprites_group = func(game24_gen.numbers_now)
elif self.attribute == 'ANSWERS':
self.font = pygame.font.Font(self.font_info[0], 20)
self.text = '[%d/%d]: ' % (game24_gen.answers_idx+1, len(game24_gen.answers)) + game24_gen.answers[game24_gen.answers_idx]
game24_gen.answers_idx = (game24_gen.answers_idx+1) % len(game24_gen.answers)
else:
raise ValueError('Button.attribute unsupport %s, expect %s, %s or %s...' % (self.attribute, 'NEXT', 'RESET', 'ANSWERS'))
return sprites_group
'''24 Click game builder '''
class game24Generator():
def __init__(self):
self.info = 'game24Generator'
''' generator '''
def generate(self):
self.__reset()
while True:
self.numbers_ori = [random.randint(1, 10) for i in range(4)]
self.numbers_now = copy.deepcopy(self.numbers_ori)
self.answers = self.__verify()
if self.answers:
break
''' When there is only one number left, check whether it is 24'''
def check(self):
if len(self.numbers_now) == 1 and float(self.numbers_now[0]) == self.target:
return True
return False
''' Reset '''
def __reset(self):
self.answers = []
self.numbers_ori = []
self.numbers_now = []
self.target = 24.
self.answers_idx = 0
''' Verify that the generated number has an answer '''
def __verify(self):
answers = []
for item in self.__iter(self.numbers_ori, len(self.numbers_ori)):
item_dict = []
list(map(lambda i: item_dict.append({str(i): i}), item))
solution1 = self.__func(self.__func(self.__func(item_dict[0], item_dict[1]), item_dict[2]), item_dict[3])
solution2 = self.__func(self.__func(item_dict[0], item_dict[1]), self.__func(item_dict[2], item_dict[3]))
solution = dict()
solution.update(solution1)
solution.update(solution2)
for key, value in solution.items():
if float(value) == self.target:
answers.append(key)
# Avoid repeating expressions when numbers are repeated (T_T Too lazy to optimize )
answers = list(set(answers))
return answers
''' Recursive enumeration '''
def __iter(self, items, n):
for idx, item in enumerate(items):
if n == 1:
yield [item]
else:
for each in self.__iter(items[:idx]+items[idx+1:], n-1):
yield [item] + each
''' Calculation function '''
def __func(self, a, b):
res = dict()
for key1, value1 in a.items():
for key2, value2 in b.items():
res.update({'('+key1+'+'+key2+')': value1+value2})
res.update({'('+key1+'-'+key2+')': value1-value2})
res.update({'('+key2+'-'+key1+')': value2-value1})
res.update({'('+key1+'×'+key2+')': value1*value2})
value2 > 0 and res.update({'('+key1+'÷'+key2+')': value1/value2})
value1 > 0 and res.update({'('+key2+'÷'+key1+')': value2/value1})
return res( Two ) The main function of the game .
def main():
# initialization , Import the necessary game material
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode(SCREENSIZE)
pygame.display.set_caption('24 A little game ')
win_sound = pygame.mixer.Sound(AUDIOWINPATH)
lose_sound = pygame.mixer.Sound(AUDIOLOSEPATH)
warn_sound = pygame.mixer.Sound(AUDIOWARNPATH)
pygame.mixer.music.load(BGMPATH)
pygame.mixer.music.play(-1, 0.0)
# 24 Click game builder
game24_gen = game24Generator()
game24_gen.generate()
# Spirit group
# -- Numbers
number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
# -- Operator
operator_sprites_group = getOperatorSpritesGroup(OPREATORS)
# -- Button
button_sprites_group = getButtonSpritesGroup(BUTTONS)
# The main cycle of the game
clock = pygame.time.Clock()
selected_numbers = []
selected_operators = []
selected_buttons = []
is_win = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(-1)
elif event.type == pygame.MOUSEBUTTONUP:
mouse_pos = pygame.mouse.get_pos()
selected_numbers = checkClicked(number_sprites_group, mouse_pos, 'NUMBER')
selected_operators = checkClicked(operator_sprites_group, mouse_pos, 'OPREATOR')
selected_buttons = checkClicked(button_sprites_group, mouse_pos, 'BUTTON')
screen.fill(AZURE)
# Update numbers
if len(selected_numbers) == 2 and len(selected_operators) == 1:
noselected_numbers = []
for each in number_sprites_group:
if each.is_selected:
if each.select_order == '1':
selected_number1 = each.attribute
elif each.select_order == '2':
selected_number2 = each.attribute
else:
raise ValueError('Unknow select_order %s, expect 1 or 2...' % each.select_order)
else:
noselected_numbers.append(each.attribute)
each.is_selected = False
for each in operator_sprites_group:
each.is_selected = False
result = calculate(selected_number1, selected_number2, *selected_operators)
if result is not None:
game24_gen.numbers_now = noselected_numbers + [result]
is_win = game24_gen.check()
if is_win:
win_sound.play()
if not is_win and len(game24_gen.numbers_now) == 1:
lose_sound.play()
else:
warn_sound.play()
selected_numbers = []
selected_operators = []
number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
# All the elves draw screen On
for each in number_sprites_group:
each.draw(screen, pygame.mouse.get_pos())
for each in operator_sprites_group:
each.draw(screen, pygame.mouse.get_pos())
for each in button_sprites_group:
if selected_buttons and selected_buttons[0] in ['RESET', 'NEXT']:
is_win = False
if selected_buttons and each.attribute == selected_buttons[0]:
each.is_selected = False
number_sprites_group = each.do(game24_gen, getNumberSpritesGroup, number_sprites_group, button_sprites_group)
selected_buttons = []
each.draw(screen, pygame.mouse.get_pos())
# Game wins
if is_win:
showInfo('Congratulations', screen)
# The game failed
if not is_win and len(game24_gen.numbers_now) == 1:
showInfo('Game Over', screen)
pygame.display.flip()
clock.tick(30)( 3、 ... and ) Game effect .


summary

This exercise thinking ability “24 A little game ” That's it ~ Take it. Thank you , Improve your math skills while playing games !
An LA ! This is the article , Your support is my biggest motivation , Remember Sanlian ~
Follow Xiaobian for more wonderful content ! Remember to click on the portal
Remember Sanlian ! If you need a complete package Source code + Free sharing of materials ! Portal

边栏推荐
- Insert sort
- 2022年高考量化卷|请各位量化考生答题
- 【Pygame合集】回忆杀-“童年游戏”,看看你中几枪?(附五款源码自取)
- Basic introduction and core components of kubernetes
- Is the financial management of qiniu school reliable and safe
- 基于CenterOS7安装Redis及常见问题解决(带图讲解)
- [auto reply Script] happy new year. I typed every word myself, not forwarded it~
- 希尔排序
- Multipartfile rename upload
- LabVIEW编程规范
猜你喜欢

Redis installation and common problem solving based on centeros7 (explanation with pictures)

LabVIEW获取Clamp函数找到的所有点的信息

LabVIEW用VISA Read函数来读取USB中断数据

LabVIEW prohibits other multi-core processing applications from executing on all cores

LabVIEW确定控件在显示器坐标系中的位置

LabVIEW图片在从16位强制转换为8位后看起来要亮或暗

HyperLeger Fabric安装

基于CenterOS7安装Redis及常见问题解决(带图讲解)

【Pygame合集】回忆杀-“童年游戏”,看看你中几枪?(附五款源码自取)

自制APP连接OneNET---实现数据监控和下发控制(MQTT)
随机推荐
MultipartFile重命名上传
怎么生成自动参考文献(简单 有图)
LabVIEW用高速数据流盘
LabVIEW编程规范
LabVIEW错误“内存已满 - 应用程序停止在节点”
集合删除元素技巧 removeIf
2022年高考量化卷|请各位量化考生答题
Four ways to add names to threads in the thread pool
How to remove the blank at the top of listview
LabVIEW使用MathScript Node或MATLAB脚本时出现错误1046
【Pygame小遊戲】別找了,休閑遊戲專題來了丨泡泡龍小程序——休閑遊戲研發推薦
LabVIEW uses the visa read function to read USB interrupt data
黑马头条丨腾讯薪酬制度改革引争议;英特尔全国扩招女工程师;黑马100%就业真的吗......
Common settings for vs
【Pygame小游戏】来了来了它来了——这款五子棋小游戏超A的,分享给你的小伙伴儿一起pk吧~
HyperLeger Fabric安装
Merge sort
Analysis of Genesis public chain
Openresty installation
【Opencv实战】这个印章“神器”够牛,节省了时间提高了效率,厉害~(附完整源码)
