current position:Home>Complete a python game in 28 minutes, "customer service play over the president card"

Complete a python game in 28 minutes, "customer service play over the president card"

2022-01-30 03:30:22 Dream eraser

This article has participated in 「 Digging force Star Program 」, Win a creative gift bag , Challenge creation incentive fund .

Prepare the material

you 're right , President and vice president of a station , Please put the professional team in the comment area .

 Zero basis to learn python How long will it take?  python Is self-study OK   free python A full set of tutorial

Later in the game , We're going to use both avatars , Make a movie full of The smell of money The game of .

The game uses Python The frame is pygame, The library is small and light , Very easy to use .

Make the game background

To make the game full of money taste , I specially made a background picture of the game . Next use pygame Let's do it .

adopt pygame.image.load Load background image , If the background image is not the right size , Can pass pygame.transform.scale Zoom the material .

import pygame
import sys
from pygame.locals import *


class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((900, 600))
        pygame.display.set_caption(" The president's turnover ")

    def set_bg(self):
        bg = pygame.image.load("images/bg.png")
        # width, height = bg.get_size()
        #  The material shrinks 
        # pygame.transform.scale(bg,(width,height))
        self.screen.blit(bg, (0, 0))

    def run(self):
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

            self.set_bg()
            pygame.display.update()


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

 Copy code 

Zoom in and out to learn the following :

#  Quick zoom ,size  identical , Zooming out increases pixel density 
pygame.transform.scale()

#  Smooth scaling ,size  Will change , Average pixel density 
pygame.transform.smoothscale()
 Copy code 

function Python Code , A picture full of money is shown in front of us .

 Zero basis to learn python How long will it take?  python Is self-study OK   free python A full set of tutorial

Now that the game is set up 900x600 size , Here's a simple calculation , How many president brands can be placed in this game window .

In order to make you see more clearly , Make an illustration , As shown below , Except for the distance between the squares , Notice the coordinates of the upper left corner of each grid in the figure below .

 Zero basis to learn python How long will it take?  python Is self-study OK   free python A full set of tutorial

Using hard coding directly , Realize the calculation of grid rendering , The following code uses pygame The elves in ,Card Class inherits from the class .

import pygame
import sys
from pygame.locals import *


class Card(pygame.sprite.Sprite):
    def __init__(self, x, y):
        self.image = pygame.image.load("images/card.png")
        width, height = self.image.get_size()
        self.rect = (x, y, width, height)


class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((900, 600))
        pygame.display.set_caption(" The president's turnover ")
        self.clock = pygame.time.Clock()
        self.start_point = (40, 45)

    def set_bg(self):
        bg = pygame.image.load("images/bg.png")
        # width, height = bg.get_size()
        #  The material shrinks 
        # pygame.transform.scale(bg,(width,height))
        self.screen.blit(bg, (0, 0))

    #  Draw a sign 
    def set_card(self):

        for num in range(7 * 4):
            if num // 7 == 0:
                x = num * 120 + 40
                y = 45
            elif num // 7 == 1:
                x = (num - 7) * 120 + 40
                y = 175
            elif num // 7 == 2:
                x = (num - 7 * 2) * 120 + 40
                y = 305
            elif num // 7 == 3:
                x = (num - 7 * 3) * 120 + 40
                y = 435
            card = Card(x, y)
            self.screen.blit(card.image, card.rect)

    def run(self):
        x = 40
        y = 45
        while True:
            self.clock.tick(60)
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

            self.set_bg()
            self.set_card()

            pygame.display.update()


if __name__ == '__main__':
    g = Game()
    g.run()
 Copy code 

The code runs as follows , Use the picture of copper coin for the card , The material was cut in advance .

 Zero basis to learn python How long will it take?  python Is self-study OK   free python A full set of tutorial

Card click events

Here's an important operation to implement , The mouse can click on the card area .

Based on the code above , A little bit of encapsulation , The specific implementation is as follows :

import pygame
import sys
from pygame.locals import *


class Card(pygame.sprite.Sprite):
    def __init__(self, x, y):
        self.image = pygame.image.load("images/card.png")
        width, height = self.image.get_size()
        self.rect = (x, y, width, height)


class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((900, 600))
        pygame.display.set_caption(" The president's turnover ")
        self.clock = pygame.time.Clock()

        self.card_nums = 28
        self.points = self.all_point()
        
	#  Encapsulating coordinate calculation functions 
    def all_point(self):
        points = []
        for num in range(self.card_nums):
            if num // 7 == 0:
                x = num * 120 + 40
                y = 45
            elif num // 7 == 1:
                x = (num - 7) * 120 + 40
                y = 175
            elif num // 7 == 2:
                x = (num - 7 * 2) * 120 + 40
                y = 305
            elif num // 7 == 3:
                x = (num - 7 * 3) * 120 + 40
                y = 435
            points.append((x, y))
        return points

    def set_bg(self):
        bg = pygame.image.load("images/bg.png")
        # width, height = bg.get_size()
        #  The material shrinks 
        # pygame.transform.scale(bg,(width,height))
        self.screen.blit(bg, (0, 0))

    #  Draw a sign 
    def set_card(self):

        for num in self.points:
            x, y = num
            card = Card(x, y)
            self.screen.blit(card.image, card.rect)

    #  Calculate the mouse click on the card 
    def mouse_card(self, mosx, mosy):
        for x, y in self.points:

            if (mosx >= x and mosx <= (x + 100)) and (mosy >= y and mosy <= (y + 100)):
                print(" O 'clock ")

    def run(self):

        while True:
            self.clock.tick(60)
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

                if event.type == MOUSEBUTTONDOWN:
                    mosx, mosy = event.pos
                    self.mouse_card(mosx, mosy)

            self.set_bg()
            self.set_card()

            pygame.display.update()

if __name__ == '__main__':
    g = Game()
    g.run()
 Copy code 

When you click on any card , It will prompt whether it is hit or not , At the same time, the coordinate generating function is encapsulated and refined .

 def all_point(self):
        points = []
        for num in range(self.card_nums):
            if num // 7 == 0:
                x = num * 120 + 40
                y = 45
            elif num // 7 == 1:
                x = (num - 7) * 120 + 40
                y = 175
            elif num // 7 == 2:
                x = (num - 7 * 2) * 120 + 40
                y = 305
            elif num // 7 == 3:
                x = (num - 7 * 3) * 120 + 40
                y = 435
            points.append((x, y))
        return points
 Copy code 

It's not enough to just get the point , It's going to take a flop , This step requires the use of Python Medium enumerate function , Loop and get the serial number at the same time .

   #  Calculate the mouse click on the card 
    def mouse_card(self, mosx, mosy):
        for i, (x, y) in enumerate(self.points):

            if (mosx >= x and mosx <= (x + 100)) and (mosy >= y and mosy <= (y + 100)):
                print(" Flop , The number of the point to the card is ", i)
 Copy code 

 Zero basis to learn python How long will it take?  python Is self-study OK   free python A full set of tutorial

Play the president's card

The above implementation is a flop trigger , The following is to realize the conversion of card surface . At this point is still used to verify the order of the card , Modify the logic code as follows , Only show the changed part of the code .

import pygame
import sys
from pygame.locals import *


class Card(pygame.sprite.Sprite):
    def __init__(self, x, y, card_state):
        self.image = pygame.image.load("images/card.png")
        width, height = self.image.get_size()
        self.rect = (x, y, width, height)
        #  Switch card faces 
        self.card_state = card_state

    def update(self):
        #  When the face of the card is  2  Show a crying face 
        if self.card_state == 2:
            self.image = pygame.image.load("images/cry.png")


class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((900, 600))
        pygame.display.set_caption(" The president's turnover ")
        self.clock = pygame.time.Clock()

        self.card_nums = 28
        self.points = self.all_point()

        #  Click on the card record array 
        self.click_list = []

    def set_bg(self):
        bg = pygame.image.load("images/bg.png")
        # width, height = bg.get_size()
        #  The material shrinks 
        # pygame.transform.scale(bg,(width,height))
        self.screen.blit(bg, (0, 0))

    #  Draw a sign 
    def set_card(self):
        for i, num in enumerate(self.points):
            x, y = num
            card_state = 1
            #  Whether the card has been clicked 
            if i in self.click_list:
                card_state = 2

            card = Card(x, y, card_state)
            card.update()
            self.screen.blit(card.image, card.rect)

    #  Calculate the mouse click on the card 
    def mouse_card(self, mosx, mosy):
        for i, (x, y) in enumerate(self.points):
            if (mosx >= x and mosx <= (x + 100)) and (mosy >= y and mosy <= (y + 100)):
                print(" Flop , The number of the point to the card is ", i)
                self.click_list.append(i)
 Copy code 

Run the code to get the following effect , One by one, one by one .

 Zero basis to learn python How long will it take?  python Is self-study OK   free python A full set of tutorial

open CSDN President's card

The game has come to the end , We can draw the president card ,Card Class adds several States , That is to say .

    def update(self):
        #  When the face of the card is  2  Show a crying face 
        if self.card_state == 2:
            self.image = pygame.image.load("images/cry.png")

        if self.card_state == 3:
            self.image = pygame.image.load("images/fuzong.png")
            self.image = pygame.transform.scale(self.image, (100, 100))

        if self.card_state == 4:
            self.image = pygame.image.load("images/zong.jpg")
            self.image = pygame.transform.scale(self.image, (100, 100))
 Copy code 

For the fun of the game , Add random effects , Use numpy Get it done .

 #  Randomly generated arrays , The winner is 1, If you don't win, it's 0
        self.win_list = list(np.random.randint(0, 3, 28))
        print(self.win_list)
 Copy code 

The final game code is :

import pygame
import sys
from pygame.locals import *
import numpy as np


class Card(pygame.sprite.Sprite):
    def __init__(self, x, y, card_state):
        self.image = pygame.image.load("images/card.png")
        width, height = self.image.get_size()
        self.rect = (x, y, width, height)
        #  Switch card faces 
        self.card_state = card_state

    def update(self):
        #  When the face of the card is  2  Show a crying face 
        if self.card_state == 2:
            self.image = pygame.image.load("images/cry.png")

        if self.card_state == 3:
            self.image = pygame.image.load("images/fuzong.png")
            self.image = pygame.transform.scale(self.image, (100, 100))

        if self.card_state == 4:
            self.image = pygame.image.load("images/zong.jpg")
            self.image = pygame.transform.scale(self.image, (100, 100))


class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((900, 600))
        pygame.display.set_caption(" The president's turnover ")
        self.clock = pygame.time.Clock()

        self.card_nums = 28
        self.points = self.all_point()

        #  Click on the card record array 
        self.click_list = []

        #  Randomly generated arrays , The winner is 1, If you don't win, it's 0
        self.win_list = list(np.random.randint(0, 3, 28))

    def all_point(self):
        pass

    def set_bg(self):
        bg = pygame.image.load("images/bg.png")
        # width, height = bg.get_size()
        #  The material shrinks 
        # pygame.transform.scale(bg,(width,height))
        self.screen.blit(bg, (0, 0))

    #  Draw a sign 
    def set_card(self):
        for i, num in enumerate(self.points):
            x, y = num
            card_state = 1
            #  Whether the card has been clicked 
            if i in self.click_list:
                card_state = 2
            #  Whether the card has been clicked 
            if i in self.click_list and self.win_list[i] == 1:
                card_state = 3
            #  Whether the card has been clicked 
            if i in self.click_list and self.win_list[i] == 2:
                card_state = 4

            card = Card(x, y, card_state)
            card.update()
            self.screen.blit(card.image, card.rect)

    #  Calculate the mouse click on the card 
    def mouse_card(self, mosx, mosy):
        for i, (x, y) in enumerate(self.points):
            if (mosx >= x and mosx <= (x + 100)) and (mosy >= y and mosy <= (y + 100)):
                print(" Flop , The number of the point to the card is ", i)
                self.click_list.append(i)

    def run(self):

        while True:
            self.clock.tick(60)
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

                if event.type == MOUSEBUTTONDOWN:
                    mosx, mosy = event.pos
                    self.mouse_card(mosx, mosy)

            self.set_bg()
            self.set_card()

            pygame.display.update()


if __name__ == '__main__':
    g = Game()
    g.run()
 Copy code 

 Zero basis to learn python How long will it take?  python Is self-study OK   free python A full set of tutorial Full code download : Download address

Please thumb up 、 Ask for comment 、 For collection .

copyright notice
author[Dream eraser],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201300330206944.html

Random recommended