In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about Python to achieve four classic Mini Game example analysis, the editor thinks it is very practical, so share it with you to learn, I hope you can get something after reading this article, say no more, follow the editor to have a look.
1. Effect display 1. Tetris
This should be the easiest to play with.
2. Mine clearance
Luckily, I didn't step on the thunder four times. Haha.
3. Gobang
I'm a vegetable chicken. I can't beat the computer guy.
4. Gluttonous Snake
Harm, this is the most thrilling, for my little heart, do not play.
Girlfriend: you just took the opportunity to play a game, and you got it
Ah, this...
Then I won't brag. Let's knock on the code.
Code display 1. Tetris
Square part
This part of the code saves the py file separately, and here I name it blocks.py
In the design of square shape, at the beginning, I made it 4 × 4, and if the longest length and width is 4, then I don't think about how to rotate, that is, I replace it from one figure to another.
To achieve this function, just fix the coordinates in the upper left corner.
Import randomfrom collections import namedtuplePoint = namedtuple ('Point',' X Y') Shape = namedtuple ('Shape',' X Y Width Height') Block = namedtuple ('Block',' template start_pos end_pos name next') # S-shaped square S_BLOCK = [Block ([.OO', 'OO.','...], Point (0,0), Point (2,1), 'slots, 1) Block (['O...', 'OO.',' .O.], Point (0,0), Point (1,2), 'slots, 0)] # Z-shaped square Z_BLOCK = [Block ([' OO.', '.Oo', '...], Point (0,0), Point (2,1) 'Zhuan, 1), Block ([' O.', 'OO.',' O..], Point (0, 0), Point (1, 2), 'Zero, 0)] # Type I square I_BLOCK = [Block ([.O..','.O..','.O..' '.O..], Point (1,0), Point (1,3),' I', 1), Block (['....,', 'OOOO','], Point (0,2), Point (3,2),'I' 0)] # O-type square O_BLOCK = [Block (['OO',' OO'], Point (0,0), Point (1,1), 'Olympus, 0)] # J-type square J_BLOCK = [Block ([' O..', 'OOO','...], Point (0,0), Point (2,1), 'Jake, 1) Block ([.OO','.O.,'.O.], Point (1,0), Point (2,2), 'Jacks, 2), Block (['...', 'OOO','.. O'], Point (0,1), Point (2,2), 'Jacks, 3) Block ([.O.','.O., 'OO.'], Point (0,0), Point (1,2),' Jacks, 0)] # L-shaped square L_BLOCK = [Block (['.. oval, 'OOO','...], Point (0,0), Point (2,1) ), Block ([.O.,'.O., '.OO'], Point (1,0), Point (2,2), 'OOO', 2), Block (['...', 'OOO',' O..], Point (0,1), Point (2,2) 'OO.', 3), Block ([' OO.','.O.,'.O.], Point (0,0), Point (1,2), 'OOO', 0)] # T-shaped square T_BLOCK = [Block ([.O.,' OOO', '...], Point (0,0) Point (2,1), 'OOO', 1), Block ([' .O.', '.OO','.O.], Point (1,0), Point (2,2), 'Toner, 2), Block (['...', 'OOO',' .O.], Point (0,1) Point (2,2), 'OO.', 3), Block ([' .O.', 'OO.',' .O.], Point (0,0), Point (1,2), 'Turing, 0)] BLOCKS = {' Orange: O_BLOCK, 'Illustrated: I_BLOCK,' Zero: Z_BLOCK, 'Turing: T_BLOCK Def get_block (): block_name = random.choice ('OIZTLSJ') b = blocks [block _ name] idx = random.randint (0, len (b)-1) return b [IDX] def get_next_block (block): B = BLOCKS [block.name] return b [block.next]
Game master code
Import sysimport timeimport pygamefrom pygame.locals import * import blocksSIZE = 30 # each small square size BLOCK_HEIGHT = 25 # Game area height BLOCK_WIDTH = 10 # Game area width BORDER_WIDTH = 4 # Game area border width BORDER_COLOR = (40,40) SCREEN_WIDTH = SIZE * (BLOCK_WIDTH + 5) # wide SCREEN_HEIGHT of game screen = SIZE * BLOCK_HEIGHT # High BG_COLOR of game screen = (40,40,60) # background color BLOCK_COLOR = (20,128,200) # BLACK = (0,0,0) RED = (200,30,30) # font color def print_text (screen, font, x, y, text Fcolor= (255,255,255): imgText = font.render (text, True, fcolor) screen.blit (imgText, (x, y)) def main (): pygame.init () screen = pygame.display.set_mode ((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption ('Tetris') font1 = pygame.font.SysFont ('SimHei', 24) # boldface 24 font2 = pygame.font.Font (None 72) # GAME OVER font font_pos_x = BLOCK_WIDTH * SIZE + BORDER_WIDTH + 10 # X coordinate of font location in the display area gameover_size = font2.size ('GAME OVER') font1_height = int (font1.size (' score') [1]) cur_block = None # current falling square next_block = None # next square cur_pos_x, cur_pos_y = 0 0 game_area = None # entire game area game_over = True start = False # whether to start or not When start = True,game_over = True GAME OVER score = 0 # score orispeed = 0.5 # original speed speed = orispeed # current speed pause = False # pause last_drop_time = None # last fall time last_press_time = None # last press time def _ dock (): nonlocal cur_block, next_block, game_area, cur_pos_x, cur_pos_y Game_over, score, speed for _ i in range (cur_block.start_pos.Y, cur_block.end_pos.Y + 1): for _ j in range (cur_block.start_pos.X Cur_block.end_pos.X + 1): if cur_ block.template[ _ I] [_ j]! ='.': game_ area [cur _ pos_y + _ I] [cur_pos_x + _ j] ='0' if cur_pos_y + cur_block.start_pos.Y = 0: while _ j in remove_idxs: _ j-= 1 if _ j
< 0: game_area[_i] = ['.'] * BLOCK_WIDTH else: game_area[_i] = game_area[_j] _i -= 1 _j -= 1 cur_block = next_block next_block = blocks.get_block() cur_pos_x, cur_pos_y = (BLOCK_WIDTH - cur_block.end_pos.X - 1) // 2, -1 - cur_block.end_pos.Y def _judge(pos_x, pos_y, block): nonlocal game_area for _i in range(block.start_pos.Y, block.end_pos.Y + 1): if pos_y + block.end_pos.Y >= BLOCK_HEIGHT: return False for _ j in range (block.start_pos.X, block.end_pos.X + 1): if pos_y + _ I > = 0 and block.template [_ I] [_ j]! ='.' And game_ area [pos _ y + _ I] [pos_x + _ j]! ='.': return False return True while True: for event in pygame.event.get (): if event.type = = QUIT: sys.exit () elif event.type = = KEYDOWN: if event.key = = K_RETURN: If game_over: start = True game_over = False score = 0 last_drop_time = time.time () last_press_time = time.time () game_area = [['.'] * BLOCK_WIDTH for _ in range (BLOCK_HEIGHT)] cur_block = blocks.get_block () next_block = blocks.get_block () cur_pos_x Cur_pos_y = (BLOCK_WIDTH-cur_block.end_pos.X-1) / / 2,-1-cur_block.end_pos.Y elif event.key = = K_SPACE: if not game_over: pause = not pause elif event.key in K_UP): if 0-cur_block.start_pos.X: if _ judge (cur_pos_x-1, cur_pos_y) Cur_block): cur_pos_x-= 1 if event.key = = pygame.K_RIGHT: if not game_over and not pause: if time.time ()-last_press_time > 0.1: last_press_time = time.time () # the right border if cur_pos_x + cur_block.end_pos.X + 1 cannot be removed
< BLOCK_WIDTH: if _judge(cur_pos_x + 1, cur_pos_y, cur_block): cur_pos_x += 1 if event.key == pygame.K_DOWN: if not game_over and not pause: if time.time() - last_press_time >Last_press_time = time.time () if not _ judge (cur_pos_x, cur_pos_y + 1) Cur_block): _ dock () else: last_drop_time = time.time () cur_pos_y + = 1 _ draw_background (screen) _ draw_game_area (screen Game_area) _ draw_gridlines (screen) _ draw_info (screen, font1, font_pos_x, font1_height, score) # draw the next square in the display message _ draw_block (screen, next_block, font_pos_x, 30 + (font1_height + 6) * 5,0 0) if not game_over: cur_drop_time = time.time () if cur_drop_time-last_drop_time > speed: if not pause: if not _ judge (cur_pos_x, cur_pos_y + 1 Cur_block): _ dock () else: last_drop_time = cur_drop_time cur_pos_y + = 1 else: if start: print_text (screen, font2 (SCREEN_WIDTH-gameover_size [0]) / / 2, (SCREEN_HEIGHT-gameover_size [1]) / / 2, 'GAME OVER', RED) # draw the current drop square _ draw_block (screen, cur_block, 0,0, cur_pos_x Cur_pos_y) pygame.display.flip () # draw background def _ draw_background (screen): # fill background color screen.fill (BG_COLOR) # draw game area separation line pygame.draw.line (screen, BORDER_COLOR, (SIZE * BLOCK_WIDTH + BORDER_WIDTH / / 2,0), (SIZE * BLOCK_WIDTH + BORDER_WIDTH / / 2) SCREEN_HEIGHT), BORDER_WIDTH) # draw grid lines def _ draw_gridlines (screen): # draw grid lines vertical for x in range (BLOCK_WIDTH): pygame.draw.line (screen, BLACK, (x * SIZE, 0), (x * SIZE, SCREEN_HEIGHT), 1) # draw grid lines for y in range (BLOCK_HEIGHT): pygame.draw.line (screen, BLACK, (0, y * SIZE) (BLOCK_WIDTH * SIZE, y * SIZE), 1) # def _ draw_game_area (screen, game_area): if game_area: for I, row in enumerate (game_area): for j, cell in enumerate (row): if cell! ='.': pygame.draw.rect (screen, BLOCK_COLOR, (j * SIZE, I * SIZE, SIZE, SIZE) 0) # draw a single square def _ draw_block (screen, block, offset_x, offset_y, pos_x, pos_y): if block: for i in range (block.start_pos.Y, block.end_pos.Y + 1): for j in range (block.start_pos.X Block.end_pos.X + 1): if block.template [I] [j]! ='.': pygame.draw.rect (screen, BLOCK_COLOR, (offset_x + (pos_x + j) * SIZE, offset_y + (pos_y + I) * SIZE, SIZE, SIZE), 0) # painting score and other information def _ draw_info (screen Font, pos_x, font_height, score): print_text (screen, font, pos_x, 10, f 'score:') print_text (screen, font, pos_x, 10 + font_height + 6, f'{score}') print_text (screen, font, pos_x, 20 + (font_height + 6) * 2, f 'Speed:') print_text (screen, font, pos_x, 20 + (font_height + 6) * 3 F'{score / / 10000}') print_text (screen, font, pos_x, 30 + (font_height + 6) * 4, f 'next:) if _ _ name__ = =' _ main__': main () 2, minesweeping
Landmine part
Similarly, save the py file separately, mineblock.py
Import randomfrom enum import EnumBLOCK_WIDTH = 30BLOCK_HEIGHT = 16SIZE = 20 # Block size MINE_COUNT = 99 # Mine number class BlockStatus (Enum): normal = 1 # unclicked opened = 2 # clicked mine = 3 # Mine flag = 4 # marked Mine ask = 5 # marked question mark bomb = 6 # Mine hint = 7 # surrounding double that is double-clicked = 8 # is being double-clicked by the left and right mouse button class Mine: def _ _ init__ (self X, y, value=0): self._x = x self._y = y self._value = 0 self._around_mine_count =-1 self._status = BlockStatus.normal self.set_value (value) def _ repr__ (self): return str (self._value) # return f'({self._x}, {self._y}) = {self._value} Status= {self.status} 'def get_x (self): return self._x def set_x (self, x): self._x = x = property (fget=get_x, fset=set_x) def get_y (self): return self._y def set_y (self, y): self._y = y = property (fget=get_y Fset=set_y) def get_value (self): return self._value def set_value (self, value): if value: self._value = 1 else: self._value = 0 value = property (fget=get_value, fset=set_value) Doc='0: non-mine 1: mine') def get_around_mine_count (self): return self._around_mine_count def set_around_mine_count (self, around_mine_count): self._around_mine_count = around_mine_count around_mine_count = property (fget=get_around_mine_count, fset=set_around_mine_count) Number of mines around doc='') def get_status (self): return self._status def set_status (self, value): self._status = value status = property (fget=get_status, fset=set_status, doc='BlockStatus') class MineBlock: def _ init__ (self): self._block = [Mine (I) J) for i in range (BLOCK_WIDTH)] for j in range (BLOCK_HEIGHT)] # Mine for i in random.sample (range (BLOCK_WIDTH * BLOCK_HEIGHT), MINE_COUNT): self._ [I / / BLOCK_WIDTH] [I% BLOCK_WIDTH] .value = 1 def get_block (self): return self._block block = property (fget=get_block) def getmine (self, x) Y): return self._ blocky [x] def open_mine (self, x Y): # stepped on if self._ block. value: self._ block. status = BlockStatus.bomb return False # change the status to opened self._ block. status = BlockStatus.opened around = _ get_around (x, y) _ sum = 0 for I J in around: if self._ blockj [I]. Value: _ sum + = 1 self._ block. around _ mine_count = _ sum # if there is no mine around Then recursively calculate the eight unopened ones around # this can achieve the effect of if _ sum = 0: for I, j in around: if self._ block[ j] [I] .around _ mine_count =-1: self.open_mine (I, j) return True def double_mouse_button_down (self) X, y): if self._ block. around _ mine_count = 0: return True self._ block. status = BlockStatus.double around = _ get_around (x, y) sumflag = 0 # number of mines marked around for I, j in _ get_around (x Y): if self._ block [j] [I]. Status = = BlockStatus.flag: sumflag + = 1 # the mines around have been marked result = True if sumflag = = self._ block [y] [x] .around _ mine_count: for I J in around: if self._ blockj [I] .status = = BlockStatus.normal: if not self.open_mine (I, j): result = False else: for I J in around: if self._ blockj [I]. Status = = BlockStatus.normal: self._ blockj] [I]. Status = BlockStatus.hint return result def double_mouse_button_up (self, x, y): self._ block. status = BlockStatus.opened for I, j in _ get_around (x) Y): if self._ block [j] [I]. Status = = BlockStatus.hint: self._ block [j] [I]. Status = BlockStatus.normaldef _ get_around (x, y): "returns the coordinates of the points around (x, y)" # Note here Range ends with an open interval, so add 1 return [(I, j) for i in range (max (0, x-1), min (BLOCK_WIDTH-1, x + 1) + 1) for j in range (max (0, y-1), min (BLOCK_HEIGHT-1, y + 1) + 1) if I! = x or j! = y]
Material
Master code
Wide SCREEN_WIDTH of import sysimport timefrom enum import Enumimport pygamefrom pygame.locals import * from mineblock import * # Game screen = BLOCK_WIDTH * High SCREEN_HEIGHT of SIZE# Game screen = (BLOCK_HEIGHT + 2) * SIZEclass GameStatus (Enum): readied = 1, started = 2, over = 3, win = 4def print_text (screen, font, x, y, text, fcolor= (255,255,255): imgText = font.render (text, True, fcolor) screen.blit (imgText) (X, y)) def main (): pygame.init () screen = pygame.display.set_mode ((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption ('minesweeping') font1 = pygame.font.Font ('resources/a.TTF', SIZE * 2) # scored font fwidth, fheight = font1.size (' 999') red = (200,40,40) # load resource picture Because resource files vary in size So img0 = pygame.image.load ('resources/0.bmp'). Convert () img0 = pygame.transform.smoothscale (img0, (SIZE, SIZE)) img1 = pygame.image.load (' resources/1.bmp'). Convert () img1 = pygame.transform.smoothscale (img1, (SIZE, SIZE)) img2 = pygame.image.load ('resources/2.bmp'). Convert () img2 = pygame.transform.smoothscale (img2, (SIZE) SIZE) img3 = pygame.image.load ('resources/3.bmp'). Convert () img3 = pygame.transform.smoothscale (img3, (SIZE, SIZE)) img4 = pygame.image.load (' resources/4.bmp'). Convert () img4 = pygame.transform.smoothscale (img4, (SIZE, SIZE) img5 = pygame.image.load ('resources/5.bmp'). Convert () img5 = pygame.transform.smoothscale (img5, (SIZE) SIZE) img6 = pygame.image.load ('resources/6.bmp'). Convert () img6 = pygame.transform.smoothscale (img6, (SIZE, SIZE)) img7 = pygame.image.load (' resources/7.bmp'). Convert () img7 = pygame.transform.smoothscale (img7, (SIZE, SIZE) img8 = pygame.image.load ('resources/8.bmp'). Convert () img8 = pygame.transform.smoothscale (img8, (SIZE) SIZE)) img_blank = pygame.image.load ('resources/blank.bmp'). Convert () img_blank = pygame.transform.smoothscale (img_blank, (SIZE, SIZE)) img_flag = pygame.image.load (' resources/flag.bmp'). Convert () img_flag = pygame.transform.smoothscale (img_flag, (SIZE) SIZE)) img_ask = pygame.image.load ('resources/ask.bmp'). Convert () img_ask = pygame.transform.smoothscale (img_ask, (SIZE, SIZE)) img_mine = pygame.image.load (' resources/mine.bmp'). Convert () img_mine = pygame.transform.smoothscale (img_mine, (SIZE) SIZE)) img_blood = pygame.image.load ('resources/blood.bmp'). Convert () img_blood = pygame.transform.smoothscale (img_blood, (SIZE, SIZE)) img_error = pygame.image.load (' resources/error.bmp'). Convert () img_error = pygame.transform.smoothscale (img_error, (SIZE) SIZE)) face_size = int (SIZE * 1.25) img_face_fail = pygame.image.load ('resources/face_fail.bmp'). Convert () img_face_fail = pygame.transform.smoothscale (img_face_fail, (face_size, face_size)) img_face_normal = pygame.image.load (' resources/face_normal.bmp'). Convert () img_face_normal = pygame.transform.smoothscale (img_face_normal, (face_size) Face_size)) img_face_success = pygame.image.load ('resources/face_success.bmp'). Convert () img_face_success = pygame.transform.smoothscale (img_face_success, (face_size, face_size)) face_pos_x = (SCREEN_WIDTH-face_size) / / 2 face_pos_y = (SIZE * 2-face_size) / / 2 img_dict = {0: img0, 1: img1 2: img2, 3: img3, 4: img4, 5: img5, 6: img6, 7: img7, 8: img8} bgcolor = (225225 Block = MineBlock () game_status = GameStatus.readied start_time = None # start time elapsed_time = 0 # time-consuming while True: # fill background color screen.fill (bgcolor) for event in pygame.event.get (): if event.type = = QUIT: sys.exit () Elif event.type = = MOUSEBUTTONDOWN: mouse_x Mouse_y = event.pos x = mouse_x / / SIZE y = mouse_y / / SIZE-2 b1, b2, b3 = pygame.mouse.get_pressed () if game_status = = GameStatus.started: # press the left and right mouse button at the same time If all mines have been marked, open a circle around # if not all mines have been marked Then there is an effect of if b1 and b3: mine = block.getmine (x, y) if mine.status = = BlockStatus.opened: if not block.double_mouse_button_down (x) Y): game_status = GameStatus.over elif event.type = = MOUSEBUTTONUP: if y < 0: if face_pos_x
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.