详解如何利⽤Python制作24点⼩游戏
⽬录
先睹为快
游戏规则(改编⾃)
逐步实现
Step1:制作24点⽣成器
Step2:定义游戏精灵类
Step3:实现游戏主循环
先睹为快
游戏规则(改编⾃)
从1~10这⼗个数字中随机抽取4个数字(可重复),对这四个数运⽤加、减、乘、除和括号进⾏运算得出24。每个数字都必须使⽤⼀次,但不能重复使⽤。
逐步实现
Step1:制作24点⽣成器
既然是24点⼩游戏,当然要先定义⼀个24点游戏⽣成器啦。主要思路就是随机⽣成4个有解的数字,且范围在1~10之间,代码实现如下:
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
在验证4个数字是否有解并求出所有解部分,我直接暴⼒枚举然后去重了,感兴趣的同学可以⾃⼰再优化⼀下求解算法(有数字重复的时候)。我的代码如下图所⽰,其实就是递归枚举所有排序然后⼀⼀验证是否有解:
'''验证⽣成的数字是否有答案'''
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)
# 避免有数字重复时表达式重复(T_T懒得优化了)
answers = list(set(answers))
return answers
'''递归枚举'''
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
'''计算函数'''
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
Step2:定义游戏精灵类
因为玩家需要通过⿏标点击来操作卡⽚,这时候就涉及到⼀些碰撞检测。所以先定义⼀些必要的游戏精灵类。
①卡⽚类
卡⽚类的定义也很简单,在屏幕上根据被赋予的属性值来显⽰⾃⾝即可。当然之后也需要根据⽤户的操作来改变这些属性值(内容、颜⾊、字体等)并在屏幕上根据属性的改变⽽改变显⽰状态即可。具体
⽽⾔代码实现如下:
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)
< = pygame.Rect(x, y, width, height)
< = 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
'''画到屏幕上'''
def draw(self, screen, mouse_pos):
(screen, self.bg_colors[1], , 0)
ollidepoint(mouse_pos):
(screen, self.bg_colors[0], , 0)
font_color = self.font_colors[self.is_selected]
text_render = , True, font_color)
font_size = self.font.)
screen.blit(text_render, (+(width-font_size[0])/2,
<+(height-font_size[1])/2))
②按钮类
按钮类和卡⽚类类似,唯⼀的不同点就是在⽤户点击按钮时需要根据该按钮的功能来响应⽤户的本次点击操作(即实现⼀次该功能)。因此只需要继承卡⽚类,然后再定义⼀个响应⽤户点击按钮事件的回调函数即可。代码实现如下:
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)
'''根据button function执⾏响应操作'''
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.attribute
萝卜干怎么腌好吃又脆self.font = pygame.font.Font(self.font_info[0], self.font_info[1])
< = self.attribute
ate()
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.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)
< = '[%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
Step3:实现游戏主循环
先构思⼀下怎么设计游戏主界⾯,个⼈的简单设计草图如下(不是特别⾛⼼的设计草图T_T):
OK,开搞。先初始化、加载必要的素材和定义必要的变量,代码实现如下:
# 初始化, 导⼊必要的游戏素材
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode(SCREENSIZE)
pygame.display.set_caption('24 point - : Charles的⽪卡丘')
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点游戏⽣成器
game24_gen = game24Generator()
ate()
# 精灵组
# --数字
number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
# --运算符
晚安温馨句子operator_sprites_group = getOperatorSpritesGroup(OPREATORS)
# --按钮
button_sprites_group = getButtonSpritesGroup(BUTTONS)
# 游戏主循环
clock = pygame.time.Clock()
selected_numbers = []
selected_operators = []
selected_buttons = []
is_win = False
游戏主循环主要分三个部分,⾸先是按键检测:
for event in ():
pe == pygame.QUIT:
pygame.quit()
pe == pygame.MOUSEBUTTONUP:
mouse_pos = _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')
根据检测结果更新卡⽚状态和⼀些变量:
'''检查控件是否被点击'''
def checkClicked(group, mouse_pos, group_type='NUMBER'):
selected = []
# 数字卡⽚/运算符卡⽚
if group_type == GROUPTYPES[0] or group_type == GROUPTYPES[1]:
max_selected = 2 if group_type == GROUPTYPES[0] else 1
num_selected = 0
for each in group:
num_selected += int(each.is_selected)
for each in group:
ollidepoint(mouse_pos):
if each.is_selected:
each.is_selected = not each.is_selected
num_selected -= 1
each.select_order = None
else:
if num_selected < max_selected:
仙剑四攻略each.is_selected = not each.is_selected
num_selected += 1
each.select_order = str(num_selected)
if each.is_selected:
selected.append(each.attribute)
# 按钮卡⽚
elif group_type == GROUPTYPES[2]:
for each in group:
ollidepoint(mouse_pos):
each.is_selected = True
selected.append(each.attribute)
# 抛出异常
else:
raise ValueError('up_type unsupport <%s>, expect <%s>, <%s> or <%s>...' % (group_type, *GROUPTYPES))
return selected
当有两个数字和⼀个运算符被点击时,则执⾏被点击数字1{+/-/×/÷}被点击数字2操作(数字1、2根据点击顺序确定),并进⼀步更新卡⽚属性和⼀些必要的变量:
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)
最后根据各个卡⽚的属性在屏幕上显⽰各个卡⽚,若游戏胜利/游戏失败,则同时显⽰游戏胜利/游戏失败提⽰框:
# 精灵都画到screen上
for each in number_sprites_group:
each.draw(screen, _pos())
for each in operator_sprites_group:
each.draw(screen, _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, _pos())
# 游戏胜利
if is_win:
showInfo('Congratulations', screen)
# 游戏失败
if not is_win and len(game24_gen.numbers_now) == 1:
机油多长时间更换showInfo('Game Over', screen)
pygame.display.flip()
clock.tick(30)
到此这篇关于详解如何利⽤Python制作24点⼩游戏的⽂章就介绍到这了,更多相关Python24点游戏内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论