In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use Python to simulate Google's Little Dinosaur Game". In daily operation, I believe many people have doubts about how to use Python to simulate Google's Little Dinosaur Game. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use Python to simulate Google's Little Dinosaur Game". Next, please follow the editor to study!
Development tools
Python version: 3.6.4
Related modules:
Pygame module; and some modules that come with python.
Environment building
Install Python and add it to the environment variable, and pip installs the relevant modules you need.
be all eagerness to see it
Run the following command on the terminal:
Python Game7.py
The effect is as follows:
Code introduction
Here is an introduction to the implementation principle of the game.
First of all, we do some necessary initialization work for the game:
# Game initialization pygame.init () screen = pygame.display.set_mode (cfg.SCREENSIZE) pygame.display.set_caption ('T-Rex Rush-Charles's Pikachu') # Import all sound files sounds = {} for key, value in cfg.AUDIO_PATHS.items (): sounds [key] = pygame.mixer.Sound (value)
Next, let's consider what game elements are in the game:
Little dinosaur: controlled by players to avoid obstacles on the road
Road: the background of the game
Cloud: the background of the game
Flying dragon: one of the obstacles on the road, the little dinosaur will die when it meets it.
Cactus: one of the obstacles on the road, the little dinosaur will die.
Scoreboard: record the current score and the highest score ever.
Let's define these game element classes in turn. For clouds, roads, and cacti, it's easy to define, we just need to load the corresponding game element pictures:
Then write two inner class methods update and draw and ok them. The two methods are used to move the scene to the left to achieve the animation effect of the small dinosaur moving forward and to display the scene in the corresponding position of the game interface. Specifically, the code implementation is as follows:
Class Ground (pygame.sprite.Sprite): def _ _ init__ (self, imagepath, position, * * kwargs): pygame.sprite.Sprite.__init__ (self) # Import picture self.image_0 = pygame.image.load (imagepath) self.rect_0 = self.image_0.get_rect () self.rect_0.left Self.rect_0.bottom = position self.image_1 = pygame.image.load (imagepath) self.rect_1 = self.image_1.get_rect () self.rect_1.left, self.rect_1.bottom = self.rect_0.right Self.rect_0.bottom # defines some necessary parameters self.speed =-10 'update the floor' 'def update (self): self.rect_0.left + = self.speed self.rect_1.left + = self.speed if self.rect_0.right
< 0: self.rect_0.left = self.rect_1.right if self.rect_1.right < 0: self.rect_1.left = self.rect_0.right '''将地板画到屏幕''' def draw(self, screen): screen.blit(self.image_0, self.rect_0) screen.blit(self.image_1, self.rect_1) '''云'''class Cloud(pygame.sprite.Sprite): def __init__(self, imagepath, position, **kwargs): pygame.sprite.Sprite.__init__(self) # 导入图片 self.image = pygame.image.load(imagepath) self.rect = self.image.get_rect() self.rect.left, self.rect.top = position # 定义一些必要的参数 self.speed = -1 '''将云画到屏幕上''' def draw(self, screen): screen.blit(self.image, self.rect) '''更新云''' def update(self): self.rect = self.rect.move([self.speed, 0]) if self.rect.right < 0: self.kill() '''仙人掌'''class Cactus(pygame.sprite.Sprite): def __init__(self, imagepaths, position=(600, 147), sizes=[(40, 40), (40, 40)], **kwargs): pygame.sprite.Sprite.__init__(self) # 导入图片 self.images = [] image = pygame.image.load(imagepaths[0]) for i in range(3): self.images.append(pygame.transform.scale(image.subsurface((i*101, 0), (101, 101)), sizes[0])) image = pygame.image.load(imagepaths[1]) for i in range(3): self.images.append(pygame.transform.scale(image.subsurface((i*68, 0), (68, 70)), sizes[1])) self.image = random.choice(self.images) self.rect = self.image.get_rect() self.rect.left, self.rect.bottom = position self.mask = pygame.mask.from_surface(self.image) # 定义一些必要的变量 self.speed = -10 '''画到屏幕上''' def draw(self, screen): screen.blit(self.image, self.rect) '''更新''' def update(self): self.rect = self.rect.move([self.speed, 0]) if self.rect.right < 0: self.kill() 记分板的定义也类似,只不过它不需要移动,但是需要实时地更新当前 的分数: '''记分板'''class Scoreboard(pygame.sprite.Sprite): def __init__(self, imagepath, position, size=(11, 13), is_highest=False, bg_color=None, **kwargs): pygame.sprite.Sprite.__init__(self) # 导入图片 self.images = [] image = pygame.image.load(imagepath) for i in range(12): self.images.append(pygame.transform.scale(image.subsurface((i*20, 0), (20, 24)), size)) if is_highest: self.image = pygame.Surface((size[0]*8, size[1])) else: self.image = pygame.Surface((size[0]*5, size[1])) self.rect = self.image.get_rect() self.rect.left, self.rect.top = position # 一些必要的变量 self.is_highest = is_highest self.bg_color = bg_color self.score = '00000' '''设置得分''' def set(self, score): self.score = str(score).zfill(5) '''画到屏幕上''' def draw(self, screen): self.image.fill(self.bg_color) for idx, digital in enumerate(list(self.score)): digital_image = self.images[int(digital)] if self.is_highest: self.image.blit(digital_image, ((idx+3)*digital_image.get_rect().width, 0)) else: self.image.blit(digital_image, (idx*digital_image.get_rect().width, 0)) if self.is_highest: self.image.blit(self.images[-2], (0, 0)) self.image.blit(self.images[-1], (digital_image.get_rect().width, 0)) screen.blit(self.image, self.rect) 上面代码用is_highest变量来区分该记分板是否用于记录游戏最高分,还是只是记录当前的分数,做该区分的原因是游戏最高分前面有HI标识,所以占的空间更大: 飞龙的定义就稍微复杂一些了,因为它不仅需要向左移动,还需要做出不停扇动翅膀的效果。具体而言,飞龙有两张图: 你需要做的就是每隔一段时间就切换一次当前的飞龙图片,以实现飞龙扇动翅膀的效果: '''飞龙'''class Ptera(pygame.sprite.Sprite): def __init__(self, imagepath, position, size=(46, 40), **kwargs): pygame.sprite.Sprite.__init__(self) # 导入图片 self.images = [] image = pygame.image.load(imagepath) for i in range(2): self.images.append(pygame.transform.scale(image.subsurface((i*92, 0), (92, 81)), size)) self.image_idx = 0 self.image = self.images[self.image_idx] self.rect = self.image.get_rect() self.rect.left, self.rect.centery = position self.mask = pygame.mask.from_surface(self.image) # 定义一些必要的变量 self.speed = -10 self.refresh_rate = 10 self.refresh_counter = 0 '''画到屏幕上''' def draw(self, screen): screen.blit(self.image, self.rect) '''更新''' def update(self): if self.refresh_counter % self.refresh_rate == 0: self.refresh_counter = 0 self.image_idx = (self.image_idx + 1) % len(self.images) self.loadImage() self.rect = self.rect.move([self.speed, 0]) if self.rect.right < 0: self.kill() self.refresh_counter += 1 '''载入当前状态的图片''' def loadImage(self): self.image = self.images[self.image_idx] rect = self.image.get_rect() rect.left, rect.top = self.rect.left, self.rect.top self.rect = rect self.mask = pygame.mask.from_surface(self.image) 最后,我们需要定义一下小恐龙类,也就是最复杂的一个游戏精灵类。它有低头,跳跃,普通前进三种状态。对于低头来说: 你只需要和飞龙扇动翅膀一样,不断切换两张低头的图片以实现小恐龙跑动的效果就可以了。对于普通状态也是类似的: 对于跳跃状态,我们则可以通过初中学的上抛和自由落体运动公式来建模,从而计算小恐龙在竖直方向上的位置。具体而言,代码实现如下: '''小恐龙'''class Dinosaur(pygame.sprite.Sprite): def __init__(self, imagepaths, position=(40, 147), size=[(44, 47), (59, 47)], **kwargs): pygame.sprite.Sprite.__init__(self) # 导入所有图片 self.images = [] image = pygame.image.load(imagepaths[0]) for i in range(5): self.images.append(pygame.transform.scale(image.subsurface((i*88, 0), (88, 95)), size[0])) image = pygame.image.load(imagepaths[1]) for i in range(2): self.images.append(pygame.transform.scale(image.subsurface((i*118, 0), (118, 95)), size[1])) self.image_idx = 0 self.image = self.images[self.image_idx] self.rect = self.image.get_rect() self.rect.left, self.rect.bottom = position self.mask = pygame.mask.from_surface(self.image) # 定义一些必要的变量 self.init_position = position self.refresh_rate = 5 self.refresh_counter = 0 self.speed = 11.5 self.gravity = 0.6 self.is_jumping = False self.is_ducking = False self.is_dead = False self.movement = [0, 0] '''跳跃''' def jump(self, sounds): if self.is_dead or self.is_jumping: return sounds['jump'].play() self.is_jumping = True self.movement[1] = -1 * self.speed '''低头''' def duck(self): if self.is_jumping or self.is_dead: return self.is_ducking = True '''不低头''' def unduck(self): self.is_ducking = False '''死掉了''' def die(self, sounds): if self.is_dead: return sounds['die'].play() self.is_dead = True '''将恐龙画到屏幕''' def draw(self, screen): screen.blit(self.image, self.rect) '''载入当前状态的图片''' def loadImage(self): self.image = self.images[self.image_idx] rect = self.image.get_rect() rect.left, rect.top = self.rect.left, self.rect.top self.rect = rect self.mask = pygame.mask.from_surface(self.image) '''更新小恐龙''' def update(self): if self.is_dead: self.image_idx = 4 self.loadImage() return if self.is_jumping: self.movement[1] += self.gravity self.image_idx = 0 self.loadImage() self.rect = self.rect.move(self.movement) if self.rect.bottom >= self.init_position [1]: self.rect.bottom = self.init_position [1] self.is_jumping = False elif self.is_ducking: if self.refresh_counter% self.refresh_rate = = 0: self.refresh_counter = 0 self.image_idx = 5 if self.image_idx = = 6 else 6 self.loadImage () else: if self.refresh_counter% self. Refresh_rate = 0: self.refresh_counter = 0 if self.image_idx = = 1: self.image_idx = 2 elif self.image_idx = = 2: self.image_idx = 3 else: self.image_idx = 1 self.loadImage () self.refresh_counter + = 1
After defining the game elf classes, we can instantiate them:
# define some essential elements and variables in the game score = 0score_board = Scoreboard (cfg.IMAGE_PATHS ['numbers'], position= (534,15), bg_color=cfg.BACKGROUND_COLOR) highest_score = highest_scorehighest_score_board = Scoreboard (cfg.IMAGE_PATHS [' numbers'], position= (435,15), bg_color=cfg.BACKGROUND_COLOR, is_highest=True) dino = Dinosaur (cfg.IMAGE_PATHS ['dino']) ground = Ground (cfg.IMAGE_PATHS [' ground'], position= (0) Cfg.SCREENSIZE [1]) cloud_sprites_group = pygame.sprite.Group () cactus_sprites_group = pygame.sprite.Group () ptera_sprites_group = pygame.sprite.Group () add_obstacle_timer = 0score_timer = 0
Then write the game main loop:
# Game main cycle clock = pygame.time.Clock () while True: for event in pygame.event.get (): if event.type = = pygame.QUIT: pygame.quit () sys.exit () elif event.type = = pygame.KEYDOWN: if event.key = = pygame.K_SPACE or event.key = = pygame.K_UP: dino.jump (sounds) elif event.key = = pygame.K_DOWN: Dino.duck () elif event.type = = pygame.KEYUP and event.key = = pygame.K_DOWN: dino.unduck () screen.fill (cfg.BACKGROUND_COLOR) #-add Cloud if len (cloud_sprites_group) randomly
< 5 and random.randrange(0, 300) == 10: cloud_sprites_group.add(Cloud(cfg.IMAGE_PATHS['cloud'], position=(cfg.SCREENSIZE[0], random.randrange(30, 75)))) # --随机添加仙人掌/飞龙 add_obstacle_timer += 1 if add_obstacle_timer >Random.randrange (50150): add_obstacle_timer = 0 random_value = random.randrange (0,10) if random_value > = 5 and random_value (cfg.FPS//12): score_timer = 0 score + = 1 score = min (score) 99999) if score > highest_score: highest_score = score if score% 1000 = 0: sounds ['point'] .play () if score% 1000 = 0: ground.speed-= 1 for item in cloud_sprites_group: item.speed-= 1 for item in cactus_sprites_group: item.speed-= 1 for item in ptera_sprites_group: item.speed-= 1 #-collision detection for item in cactus_sprites_group: if pygame.sprite.collide_mask (dino Item): dino.die (sounds) for item in ptera_sprites_group: if pygame.sprite.collide_mask (dino Item): dino.die (sounds) #-draw game elements onto the screen dino.draw (screen) ground.draw (screen) cloud_sprites_group.draw (screen) cactus_sprites_group.draw (screen) ptera_sprites_group.draw (screen) score_board.set (score) highest_score_board.set (highest_score) score_board.draw (screen) highest_score_board.draw (screen) #- -Update the screen pygame.display.update () clock.tick (cfg.FPS) #-- whether the game is over if dino.is_dead: break
The logic of the main cycle of the game is very simple, that is, every frame of the game screen, we need to test the player's operation. If the player presses the space bar or ↑ key, the small dinosaur jumps. If the player presses the ↓ key, the small dinosaur bows its head, otherwise the small dinosaur rushes forward normally.
Then in the game, we randomly generate game scenes and obstacles such as clouds, dragons and cacti, and move to the left at the same speed as the road, thus realizing the visual effect of the little dinosaur moving to the right. In the process of moving, we need to detect the collision between the little dinosaur and the cactus, the little dinosaur and the flying dragon. When the little dinosaur hits these obstacles, the little dinosaur dies, and the game ends.
It is important to note that we should use the collide_mask function for more accurate collision detection instead of the previous collide_rect function:
That is, when the minimum circumscribed rectangles of the two targets overlap, collide_rect will determine that the two targets collide, which is obviously unreasonable and will bring a poor game experience to the players.
In addition, when the score increases by a thousand points, we increase the speed at which the scene and obstacles move to the left as in the original game (that is, the speed at which the little dinosaur moves to the right).
Finally, bind all the current game elements to the screen and update the current screen to ok.
At this point, the study on "how to use Python to simulate Google's little dinosaur game" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.