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 .
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 .
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 .
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 .
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
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 .
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
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
The sidebar is recommended
- Getting started with Python - object oriented - special methods
- Using linear systems in python with scipy.linalg
- Fast power modulus Python implementation of large numbers
- Python architects recommend the book "Python programmer's Guide" which must be read by self-study Python architects. You are welcome to take it away
- Decoding the verification code of Taobao slider with Python + selenium, the road of information security
- Python game development, pyGame module, python implementation of skiing games
- Python collects and monitors system data -- psutil
- Python + selenium automated test: page object mode
- You can easily get started with Excel. Python data analysis package pandas (IV): any grouping score bar
- Python ThreadPoolExecutor restrictions_ work_ Queue size
guess what you like
-
Python generates and deploys verification codes with one click (Django)
-
[Python kaggle] pandas basic exercises in machine learning series (6)
-
Using linear systems in python with scipy.linalg
-
Using Python to realize national second-hand housing data capture + map display
-
How to make Python run faster? Six tips!
-
Python chat room (Tkinter writing interface, streaming, socket to realize private chat, group chat, check chat records, Mysql to store data)
-
This pandas exercise must be successfully won
-
[algorithm learning] sword finger offer 64 Find 1 + 2 +... + n (Java / C / C + + / Python / go / trust)
-
Understand Python's built-in function and add a print function yourself
-
Python implements JS encryption algorithm in thousands of music websites
Random recommended
- leetcode 35. Search Insert Position(python)
- [introduction to Python visualization]: 12 small examples of complete data visualization, taking you to play with visualization ~
- Learning this Python library can reduce at least 100 lines of code
- leetcode 67. Add Binary(python)
- Regular re parameter replacement of Python 3 interface automation test framework
- V. pandas based on Python
- Only 15 lines of code is needed for face detection! (using Python and openCV)
- [Python crawler Sao operation] you can crawl Sirius cinema movies without paying
- leetcode 69. Sqrt(x)(python)
- Teach you to read the source code of Cpython (I)
- Snowball learning started in the fourth quarter of Python. One needs three meals. I have a new understanding of Python functional programming, process-oriented, object-oriented and functional
- leetcode 88. Merge Sorted Array(python)
- Don't you know more about a python library before the end of 2021?
- Python crawler web page parsing artifact XPath quick start teaching!!!
- Use Python and OpenCV to watermark the image
- String and related methods of Python data type introduction
- Heapq module of Python module
- Introduction to beautiful soup of Python crawler weapon, detailed explanation, actual combat summary!!!
- Event loop of Python collaboration series
- Django docking pin login system
- [recalling the 1970s] using Python to repair the wonderful memories of parents' generation, black-and-white photos become color photos
- You used to know Python advanced
- Pyinstaller package Python project
- 2021 IEEE programming language rankings: Python tops the list!
- Implementation of Python automatic test control
- Python advanced: [Baidu translation reverse] graphic and video teaching!!!
- Do you know the fuzzy semantics in Python syntax?
- [Python from introduction to mastery] (XXVII) learn more about pilot!
- Playing excel office automation with Python
- Some applications of heapq module of Python module
- Python and go languages are so popular, which is more suitable for you?
- Python practical skills task segmentation
- Python simulated Login, numpy module, python simulated epidemic spread
- Python opencv contour discovery function based on image edge extraction
- Application of Hoff circle detection in Python opencv
- Python reptile test ox knife (I)
- Day 1: learn the Django framework of Python development
- django -- minio_ S3 file storage service
- [algorithm learning] 02.03 Delete intermediate nodes (Java / C / C + + / Python / go)
- Learning in Python + opencv -- extracting corners