Pygame practice: are the children at home poor in math? Don't panic - this "clever 24 point game" is waiting for you to play, and it works.

Introduction

Hello! Daily game update series - kimiko is coming again! Today we are talking about a game that everyone is familiar with!

The first time I played 24:00 was in junior high school. At that time, I played with my cousin at my cousin's house. My cousin proposed to play 24:00. My cousin was better than me

They are three years younger. Maybe they are in primary school.

Take out a deck of playing cards, remove the size monsters and cards, and randomly find four cards from the remaining cards. Who can calculate 24 with addition, subtraction, multiplication and division first

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, don

My sister is obviously prepared.

In fact, 24:00 games can not only be used to play with friends when they are bored, but also exercise their thinking ability, especially 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 math becomes

Children are more interested after the game~

Today, mumuzi will take you to write a "24 point game" with interface

text

Introduction to the game:

(1) What is a 24 point game?

Chess and card puzzle games require the result to be equal to 24

(2) The rules of the game.

Take 4 numbers (1-10) arbitrarily, and calculate the number into 24 with addition, subtraction, multiplication and division (parentheses can be added). Each number must be

It must be used once and only once. As an intellectual game to exercise thinking, we should also pay attention to the skills in calculation. meter

When calculating, we can't try the different combination forms of the four numbers on the card, let alone touch them blindly.

Example: 3, 8, 8, 9

Answer: 3 × 8÷(9-8)=24

(1) Define this part of the game code in lowercase game.py file.

'''

    Define game

'''
import copy
import random
import pygame


'''
Function:
    Card class
Initial Args:
    --x,y: Upper left coordinate
    --width: wide
    --height: high
    --text: text
    --font: [Font path, font size]
    --font_colors(list): 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 to 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 a 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 Point game generator'''
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 repetition of expressions when there are repeated numbers (T_T is 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

(2) Game main function.

def main():
    # Initialize and import necessary game materials
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode(SCREENSIZE)
    pygame.display.set_caption('24 Some games')
    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 point game generator
    game24_gen = game24Generator()
    game24_gen.generate()
    # Sprite group
    # --Number
    number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
    # --Operator
    operator_sprites_group = getOperatorSpritesGroup(OPREATORS)
    # --Push button
    button_sprites_group = getButtonSpritesGroup(BUTTONS)
    # Game main loop
    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 number
        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)
        # The elves are painted on the screen
        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 victory
        if is_win:
            showInfo('Congratulations', screen)
        # Game failure
        if not is_win and len(game24_gen.numbers_now) == 1:
            showInfo('Game Over', screen)
        pygame.display.flip()
        clock.tick(30)

(3) Game effects.

โ€‹

summary

This "24 o'clock game" to exercise your thinking ability is completed ~ you're welcome to take it. Play the game and improve your math ability!

๐ŸŽฏ Complete free source code collection:

For the complete project source code + material source code base, see: # private letter editor 06# or click the blue text to add to get free benefits!

Previous game recommendations——

Item 1.1     mine clearance

  Pygame actual combat: it is said that this is the most difficult minesweeping game in history. There is no one. Feel it

Item 1.2     Contra

Pygame actual combat: many years later, the pixel style of "soul duel" returned, not just classics and feelings @ all members

Item 1.3   Space mecha game

Pygame actual combat: cow, thousands of lines of code to realize the "mecha breakthrough adventure game", which is great (save it and learn it slowly)

Item 1.4   Fruit ninja

[Pygame actual combat] the upgraded version of fruit cutting game "fruit ninja" which is popular all over the world has been launched. Do you dare to PK?

๐Ÿ“ Article summary——

Item 1.0   Python-2021 | summary of existing articles | continuously updated. It's enough to read this article directly

(more content + source code are summarized in the article!! welcome to read ~)

Tags: Python pygame

Posted on Sat, 27 Nov 2021 20:22:47 -0500 by linusx007