Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Use Python to explain what hardcore dad is


May 31, 2021 Article blog


Table of contents


This article comes from the public number: Python Technology Author: Pieson Sauce

A few days ago, to my son bought a flying chess, even like, every day to come with me two sets, yesterday ready to fight a war, found that the dice lost, no dice can not play, just want to use the eraser to do one, suddenly thought of a better way, after a toss, finally finished, the result ...

Idea

The dice are cubes, with six faces, each with different locations, from 1 to 6, representing 1 to 6 six numbers, and when you play, roll the dice, wait until it stops, and the face up is a few points, which means a few.

In different games, there are different ways to play the number of points you hit, such as flying chess, shaking to 5 or 6, and taking off a plane.

 Use Python to explain what hardcore dad is1

Now I need to use a program to simulate this process, in fact, is to produce 1 to 6 direct random numbers, directly with random.randint(1, 6) can be done, but I do not want to do so simple, one is for children, directly give the number is not intuitive enough, and the other is, can have the opportunity to give a son a stunt, why not?

So the idea is as follows:

  • Looking for some dice material, you need to have a picture of each number up
  • In order to create the rotation effect of the dice, you also need some pictures in the middle of the rotation
  • Randomly produce numbers between 0 and 5, 0 for points 1,1 for points 2, and so on, 5 for points 6, why not just generate 1 to 6? There's an answer later
  • The dice roll process has two states, that is, to show points and rotation, then there needs to be a trigger mechanism, considering that children are not flexible mouse operation, choose the space bar to control, press is equivalent to throwing once

implement

After the idea is well conceived, hurry to achieve!

material

First from the Internet to find some dice material, and finally selected WeChat roll dice emoticon as an element of a series of gif pictures, through the picture resolution tool, extracted from the gif picture each frame, including the point-up picture, and turn the middle of the picture, so that the picture material is done.

In practice, if it is not convenient to obtain picture footage, you can get it from the sample code in this article

Next, it's the programming section, using pygame, a python game engine library.

dice

First, write a dice class that defines the various resources of the dice and manages the status of the dice, as follows:

import random
import pygame


class Dice:
    def __init__(self):
        self.diceRect = pygame.Rect(200, 225, 100, 100)
        self.diceSpin = [
            pygame.image.load("asset/rolling/4.png"),
            pygame.image.load("asset/rolling/3.png"),
            pygame.image.load("asset/rolling/2.png"),
            pygame.image.load("asset/rolling/1.png")
        ]
        self.diceStop = [
            pygame.image.load("asset/dice/1.png"),
            pygame.image.load("asset/dice/2.png"),
            pygame.image.load("asset/dice/3.png"),
            pygame.image.load("asset/dice/4.png"),
            pygame.image.load("asset/dice/5.png"),
            pygame.image.load("asset/dice/6.png")
        ]


        self.StopStatus = random.randint(0, 5)
        self.SpinStatus = 0


    def move(self):
        self.SpinStatus += 1
        if self.SpinStatus == len(self.diceSpin):
            self.SpinStatus = 0

  • In the initialization method, pygame.Rect method sets a rectangular area, i.e. the game window coordinates (200, 225) and the height and width are 100, which is used to draw the dice in the game window
  • diceSpin stores the picture footage during the dice rotation, noting that the picture resource needs to be loaded with pygame.image.load
  • DiceStop stores picture footage of dice points
  • StopStatus records the point value of the dice stop state and initializes it to a random number between 0 and 5
  • SpinStatus records the picture index of the current frame during rotation, which defaults to 0
  • The move method is equivalent to a rotating controller, changing the index of the picture in rotation once each time it is called, and the dice are called repeatedly during the rotation of the dice

engine

Next, write a game engine class that drives the game, as follows:

import random
import sys
import pygame


class Game:
    def __init__(self, width=500, height=600):
        pygame.init()
        size = width, height
        self.screen = pygame.display.set_mode(size)
        self.clock = pygame.time.Clock()
        self.screen.fill((255, 255, 255))


        self.rollTimes = 0  # 掷骰子过程的帧数记录
        self.Dice = Dice()
        self.start = False  # 状态标识
        self.rollCount = random.randint(3, 10)  # 初始投掷帧数


    def roll(self):
        self.screen.blit(self.Dice.diceSpin[self.Dice.SpinStatus], self.Dice.diceRect)
        self.Dice.move()
        self.rollTimes += 1
        if self.rollTimes > self.rollCount:
            self.start = False
            self.rollCount = random.randint(3, 10)
            self.Dice.StopStatus = random.randint(0, 5)
            self.rollTimes = 0


    def stop(self):
        self.screen.blit(self.Dice.diceStop[self.Dice.StopStatus], self.Dice.diceRect)


    def run(self):
        while True:
            self.clock.tick(10)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if ((event.type == pygame.KEYDOWN and event.key==pygame.K_SPACE) \
                or event.type == pygame.MOUSEBUTTONDOWN) \
                and self.start == False:
                    self.start = True


            if self.start:
                self.roll()
            else:
                self.stop()
            pygame.display.update()

  • In the initialization method, the game window is initialized, the window size is set, and then the control class variables in the process are initialized
  • The roll method is a toss, and is called repeatedly during the toss, first setting up a picture in transit, and then calling the move method of the dice to get a new rotation state
  • In the roll method, the next step is a controller that stops and gets random points if the set number of turns is reached
  • The stop method, called when the rotation is stopped, draws the picture of the points when the rotation stops to the window, where StopStatus range is 0 to 5, which corresponds exactly to the index of diceStop list, which is why the random number range is 0 to 5
  • The run method is the engine's start-up portal, which starts an event loop
  • Loop, check the event record again, and if an exit event is received, the loop is closed
  • If you receive a space bar or mouse button that is pressed and the throwing state is stopped, set the throwing state to start
  • After checking the event record, determine the throwing state, and if it is the start state, call roll method, otherwise call stop method
  • The last loop requires a call pygame.display.update() to refresh the window once

Here's a description of clock.tick which is used to make the loop execute how many times per second, abstractly, as animated frames, that is, how many frames per second.

We are more familiar with clock.tick which indicates how long to wait before executing, and then the effect of clock.tick(10) is equivalent to time.sleep(0.1) that is, 10 executions per second, which is equivalent to one tenth of a second at a time. time.sleep

run

if __name__ == '__main__':
    Game().run()

Note: Switch the directory to run under the code catalog, or you may be prompted that the picture file cannot be found.

Here's how it works, like this:

 Use Python to explain what hardcore dad is2

After tossing, I can't wait to go to my son to show off, as a result, he has fallen asleep, surrounded by some flying pieces ...

summary

Whether in life or work, programming skills are becoming more and more important, programming has become a tool for thinking and creating, learn a programming skills, not only can help themselves, perhaps can save a child programming costs, in improving children's logical thinking ability at the same time, but also to enhance the feelings with children, I have to say, when my son used the dice I wrote to play flying chess, more happy.

To be a hardcore parent, I use Python!

That's W3Cschool编程狮 has to say about using Python to explain what a hard-core dad is called, and I hope it will help you.