current position：Home>Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)
Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)
2022-01-30 07:08:15 【Dai mubai】
Little knowledge , Great challenge ！ This article is participating in “ A programmer must have a little knowledge ” Creative activities
The next few issues , I will take you hand in hand to realize the magic tower game from scratch ( It's the picture that old friends used to play when they were young
Python edition ： 3.7.4
Related modules ：
pygame modular ;
As well as some python Built in modules .
install Python And add to environment variable ,pip Install the relevant modules required .
Introduction of the principle
First , We open the start interface of the original game , It turns out that ：
To be specific , Our idea is to define a button class first , To simulate... In the original game “ Start the game ”,“ Game Description ” and “ Leave the game ” The functions of these three keys ：
''' Button class ''' class Button(pygame.sprite.Sprite): def __init__(self, text, fontpath, fontsize, position, color_selected=(255, 0, 0), color_default=(255, 255, 255)): pygame.sprite.Sprite.__init__(self) self.text = text self.color_selected = color_selected self.color_default = color_default self.font = pygame.font.Font(fontpath, fontsize) self.font_render = self.font.render(text, True, color_default) self.rect = self.font_render.get_rect() self.rect.center = position ''' Update function : Constantly update to detect whether the mouse is on the button ''' def update(self): mouse_pos = pygame.mouse.get_pos() if self.rect.collidepoint(mouse_pos): self.font_render = self.font.render(self.text, True, self.color_selected) else: self.font_render = self.font.render(self.text, True, self.color_default) ''' Bind to the screen ''' def draw(self, screen): screen.blit(self.font_render, self.rect) Copy code
The main principle is to constantly detect whether the mouse is in the corresponding button area , If in , Change the color of the button ( Here it turns red ), Otherwise, the button uses the default color ( This is white ), To show the player that this is a clickable button .
then , Let's instantiate it three times to add these three buttons to the game start interface ：
''' Game start screen ''' class StartGameInterface(): def __init__(self, cfg): self.cfg = cfg self.play_btn = Button(' Start the game ', cfg.FONTPATH_CN, 50, (cfg.SCREENSIZE//2, cfg.SCREENSIZE - 400)) self.intro_btn = Button(' Game Description ', cfg.FONTPATH_CN, 50, (cfg.SCREENSIZE//2, cfg.SCREENSIZE - 300)) self.quit_btn = Button(' Leave the game ', cfg.FONTPATH_CN, 50, (cfg.SCREENSIZE//2, cfg.SCREENSIZE - 200)) ''' External call ''' def run(self, screen): # Magic tower font = pygame.font.Font(self.cfg.FONTPATH_CN, 80) font_render_cn = font.render(' Magic tower ', True, (255, 255, 255)) rect_cn = font_render_cn.get_rect() rect_cn.center = self.cfg.SCREENSIZE // 2, 200 # Magic Tower font = pygame.font.Font(self.cfg.FONTPATH_EN, 80) font_render_en = font.render('Magic Tower', True, (255, 255, 255)) rect_en = font_render_en.get_rect() rect_en.center = self.cfg.SCREENSIZE // 2, 350 # (Ver 1.12) font = pygame.font.Font(self.cfg.FONTPATH_CN, 40) font_render_version = font.render('(Ver 1.12)', True, (255, 255, 255)) rect_ver = font_render_version.get_rect() rect_ver.center = self.cfg.SCREENSIZE // 2, 400 clock = pygame.time.Clock() while True: screen.fill((0, 0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(0) elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: mouse_pos = pygame.mouse.get_pos() if self.play_btn.rect.collidepoint(mouse_pos): return True elif self.quit_btn.rect.collidepoint(mouse_pos): pygame.quit() sys.exit(0) elif self.intro_btn.rect.collidepoint(mouse_pos): self.showgameintro(screen) for btn in [self.intro_btn, self.play_btn, self.quit_btn]: btn.update() btn.draw(screen) for fr, rect in zip([font_render_cn, font_render_en, font_render_version], [rect_cn, rect_en, rect_ver]): screen.blit(fr, rect) pygame.display.flip() clock.tick(self.cfg.FPS) ''' Show game Introduction ''' def showgameintro(self, screen): font = pygame.font.Font(self.cfg.FONTPATH_CN, 20) font_renders = [ font.render(' Magic Tower Games .', True, (255, 255, 255)), font.render(' The game material comes from : http://www.4399.com/flash/1749_1.htm.', True, (255, 255, 255)), font.render(' The background story of the game is that the princess is captured by the demon king , Warriors need to go to the magic tower to rescue them .', True, (255, 255, 255)), font.render('python Engineering lion .', True, (255, 255, 255)), font.render(' WeChat official account : python Engineering lion .', True, (255, 255, 255)), font.render(' copyright .', True, (255, 255, 255)), ] rects = [fr.get_rect() for fr in font_renders] for idx, rect in enumerate(rects): rect.center = self.cfg.SCREENSIZE // 2, 50 * idx + 100 clock = pygame.time.Clock() while True: screen.fill((0, 0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(0) elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: mouse_pos = pygame.mouse.get_pos() if self.play_btn.rect.collidepoint(mouse_pos): return True elif self.quit_btn.rect.collidepoint(mouse_pos): pygame.quit() sys.exit(0) elif self.intro_btn.rect.collidepoint(mouse_pos): return for btn in [self.intro_btn, self.play_btn, self.quit_btn]: btn.update() btn.draw(screen) for fr, rect in zip(font_renders, rects): screen.blit(fr, rect) pygame.display.flip() clock.tick(self.cfg.FPS) Copy code
Other additional code mainly displays information such as the title of the game , All very simple. , I won't discuss it in detail , Meeting pygame I'm sure all my friends can write it out
Next , Let's see what the interface looks like after the game starts
To be specific , We can first define the appearance of the game map in the text file , Similar to the figure below , Each number represents a game element ：
I have also collected the game materials sorted out by others found on the Internet ：
therefore , We can write a game map file parsing class , Just like this. ：
''' Game map analysis class ''' class MapParser(): def __init__(self, blocksize, filepath, element_images, offset=(0, 0), **kwargs): self.count = 0 self.switch_times = 15 self.image_pointer = 0 self.offset = offset self.blocksize = blocksize self.element_images = element_images self.map_matrix = self.parse(filepath) ''' analysis ''' def parse(self, filepath): map_matrix =  with open(filepath, 'r') as fp: for line in fp.readlines(): line = line.strip() if not line: continue map_matrix.append([c.strip() for c in line.split(',')]) return map_matrix ''' Draw the game map to the screen ''' def draw(self, screen): self.count += 1 if self.count == self.switch_times: self.count = 0 self.image_pointer = int(not self.image_pointer) for row_idx, row in enumerate(self.map_matrix): for col_idx, elem in enumerate(row): position = col_idx * self.blocksize + self.offset, row_idx * self.blocksize + self.offset if elem+'.png' in self.element_images: image = self.element_images[elem+'.png'][self.image_pointer] image = pygame.transform.scale(image, (self.blocksize, self.blocksize)) screen.blit(image, position) Copy code
among parse The function is actually to read the text file that stores the game map information , then draw The function is actually based on the read map information , Bind the corresponding game element picture to the map for display . in addition ,image_pointer,switch_times,count These three variables are used to achieve the flickering effect of scene elements in the original map , Just like this. ：
According to this principle , We can easily draw the original map in all layers of the magic tower , The defined game map file is shown in the figure below ：
The effect is shown below ：
ok, To sum up , It is this issue that mainly realizes the initial picture of each layer in the magic tower game , For the complete source code of this issue, please refer to the introduction of your home page
This is the end of the article , Thanks for watching ,Python28 A series of small games , The next article shares Magic Tower Games （2）
To thank readers , I want to share with you some of my recent collections of programming dry goods , Give back to every reader , I hope I can help you .
Tomorrow I will take you to further reproduce the magic tower game , Interested partners can pay more attention to ~
author[Dai mubai],Please bring the original link to reprint, thank you.
The sidebar is recommended
- [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
guess what you like
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)
Similarities and differences of five pandas combinatorial functions
- Learning in Python + opencv -- extracting corners
- Python beginner's eighth day ()
- Necessary knowledge of Python: take you to learn regular expressions from zero
- Get your girlfriend's chat records with Python and solve the paranoia with one move
- My new book "Python 3 web crawler development practice (Second Edition)" has been recommended by the father of Python!
- From zero to familiarity, it will take you to master the use of Python len() function
- Python type hint type annotation guide
- leetcode 108. Convert Sorted Array to Binary Search Tree（python）
- For the geometric transformation of Python OpenCV image, let's first talk about the extraordinary resize function
- leetcode 701. Insert into a Binary Search Tree （python）
- For another 3 days, I sorted out 80 Python datetime examples, which must be collected!
- Python crawler actual combat | using multithreading to crawl lol HD Wallpaper
- Complete a python game in 28 minutes, "customer service play over the president card"
- The universal Python praise machine (commonly known as the brushing machine) in the whole network. Do you want to know the principle? After reading this article, you can write one yourself
- How does Python compare file differences between two paths
- Common OS operations for Python
- [Python data structure series] linear table - explanation of knowledge points + code implementation
- How Python parses web pages using BS4
- How do Python Network requests pass parameters
- Python core programming - decorator
- Python Network Programming -- create a simple UPD socket to realize mutual communication between two processes
- leetcode 110. Balanced Binary Tree（python）
- Django uses Django celery beat to dynamically add scheduled tasks
- The bear child said "you haven't seen Altman" and hurriedly studied it in Python. Unexpectedly
- Optimization iteration of nearest neighbor interpolation and bilinear interpolation algorithm for Python OpenCV image
- Bilinear interpolation algorithm for Python OpenCV image, the most detailed algorithm description in the whole network
- Use of Python partial()
- Python game development, pyGame module, python implementation of angry birds
- leetcode 1104. Path In Zigzag Labelled Binary Tree（python）
- Save time and effort. 10 lines of Python code automatically clean up duplicate files in the computer
- Learn python, know more meat, and be a "meat expert" in the technical circle. One article is enough
- [Python data structure series] "stack (sequential stack and chain stack)" -- Explanation of knowledge points + code implementation
- Datetime module of Python time series
- Python encrypts and decrypts des to solve the problem of inconsistency with Java results
- Chapter 1: introduction to Python programming-4 Hello World
- Summary of Python technical points
- 11.5K Star！ An open source Python static type checking Library
- Chapter 2: Fundamentals of python-1 grammar
- [Python daily homework] day4: write a function to count the number of occurrences of each number in the incoming list and return the corresponding dictionary.
- Python uses turtle to express white