Pygame series _ elephant game

Source: Internet
Author: User

This game was originally named:Chimp, We can go:

Http://www.pygame.org/docs/tut/chimp/ChimpLineByLine.html

Get the source code and detailed explanation of the source code

The following is my adaptation of the game:

Running effect:

When the arrow stabbed the elephant, the elephant's body would flip and make a sound. Of course, when it didn't, it would make another sound.

In the game, there are many places worth our reference, such as loading images, sound and exception handling.

========================================================== =

Code Section:

========================================================== =

  1 #python elephant  2   3 #Import Modules  4 import os, pygame  5 from pygame.locals import *  6   7 __author__ = {‘name‘ : ‘Hongten‘,  8               ‘mail‘ : ‘[email protected]‘,  9               ‘blog‘ : ‘http://www.cnblogs.com/hongten‘, 10               ‘QQ‘   : ‘648719819‘, 11               ‘Version‘ : ‘1.0‘} 12  13 if not pygame.font: print(‘Warning, fonts disabled‘) 14 if not pygame.mixer: print(‘Warning, sound disabled‘) 15  16  17 #functions to create our resources 18 def load_image(name, colorkey=None): 19     fullname = os.path.join(‘data‘, name) 20     try: 21         image = pygame.image.load(fullname) 22     except pygame.error as message: 23         print(‘Cannot load image:‘, fullname) 24         raise (SystemExit, message) 25     image = image.convert() 26     if colorkey is not None: 27         if colorkey is -1: 28             colorkey = image.get_at((0,0)) 29         image.set_colorkey(colorkey, RLEACCEL) 30     return image, image.get_rect() 31  32 def load_sound(name): 33     class NoneSound: 34         def play(self): pass 35     if not pygame.mixer or not pygame.mixer.get_init(): 36         return NoneSound() 37     fullname = os.path.join(‘data‘, name) 38     try: 39         sound = pygame.mixer.Sound(fullname) 40     except pygame.error as message: 41         print(‘Cannot load sound:‘, fullname) 42         raise (SystemExit, message) 43     return sound 44  45  46 #classes for our game objects 47 class Spear(pygame.sprite.Sprite): 48     """moves a clenched spear on the screen, following the mouse""" 49     def __init__(self): 50         pygame.sprite.Sprite.__init__(self) #call Sprite initializer 51         self.image, self.rect = load_image(‘spear-w.png‘, -1) 52         self.punching = 0 53  54     def update(self): 55         "move the spear based on the mouse position" 56         pos = pygame.mouse.get_pos() 57         self.rect.midtop = pos 58         if self.punching: 59             self.rect.move_ip(5, 10) 60  61     def punch(self, target): 62         "returns true if the spear collides with the target" 63         if not self.punching: 64             self.punching = 1 65             hitbox = self.rect.inflate(-5, -5) 66             return hitbox.colliderect(target.rect) 67  68     def unpunch(self): 69         "called to pull the spear back" 70         self.punching = 0 71  72  73 class Elephant(pygame.sprite.Sprite): 74     """moves a elephant critter across the screen. it can spin the 75        monkey when it is punched.""" 76     def __init__(self): 77         pygame.sprite.Sprite.__init__(self) #call Sprite intializer 78         self.image, self.rect = load_image(‘elephant-nw.png‘, -1) 79         screen = pygame.display.get_surface() 80         self.area = screen.get_rect() 81         self.rect.topleft = 10, 10 82         self.move = 9 83         self.dizzy = 0 84  85     def update(self): 86         "walk or spin, depending on the monkeys state" 87         if self.dizzy: 88             self._spin() 89         else: 90             self._walk() 91  92     def _walk(self): 93         "move the monkey across the screen, and turn at the ends" 94         newpos = self.rect.move((self.move, 0)) 95         if self.rect.left < self.area.left or  96            self.rect.right > self.area.right: 97             self.move = -self.move 98             newpos = self.rect.move((self.move, 0)) 99             self.image = pygame.transform.flip(self.image, 1, 0)100         self.rect = newpos101 102     def _spin(self):103         "spin the monkey image"104         center = self.rect.center105         self.dizzy = self.dizzy + 12106         if self.dizzy >= 360:107             self.dizzy = 0108             self.image = self.original109         else:110             rotate = pygame.transform.rotate111             self.image = rotate(self.original, self.dizzy)112         self.rect = self.image.get_rect(center=center)113 114     def punched(self):115         "this will cause the monkey to start spinning"116         if not self.dizzy:117             self.dizzy = 1118             self.original = self.image119 120 121 def main():122     """this function is called when the program starts.123        it initializes everything it needs, then runs in124        a loop until the function returns."""125 #Initialize Everything126     pygame.init()127     screen = pygame.display.set_mode((468, 60))128     pygame.display.set_caption(‘Monkey Fever‘)129     pygame.mouse.set_visible(0)130 131 #Create The Backgound132     background = pygame.Surface(screen.get_size())133     background = background.convert()134     background.fill((250, 250, 250))135 136 #Put Text On The Background, Centered137     if pygame.font:138         font = pygame.font.Font(None, 36)139         text = font.render("Pummel The Elephant, And Win $$$", 1, (10, 10, 10))140         textpos = text.get_rect(centerx=background.get_width()/2)141         background.blit(text, textpos)142 143 #Display The Background144     screen.blit(background, (0, 0))145     pygame.display.flip()146 147 #Prepare Game Objects148     clock = pygame.time.Clock()149     whiff_sound = load_sound(‘elephant-jump.wav‘)150     punch_sound = load_sound(‘elephant-mmove.wav‘)151     elephant = Elephant()152     spear = Spear()153     allsprites = pygame.sprite.RenderPlain((spear, elephant))154 155 #Main Loop156     while 1:157         clock.tick(60)158 159     #Handle Input Events160         for event in pygame.event.get():161             if event.type == QUIT:162                 return163             elif event.type == KEYDOWN and event.key == K_ESCAPE:164                 return165             elif event.type == MOUSEBUTTONDOWN:166                 if spear.punch(elephant):167                     punch_sound.play() #punch168                     elephant.punched()169                 else:170                     whiff_sound.play() #miss171             elif event.type is MOUSEBUTTONUP:172                 spear.unpunch()173 174         allsprites.update()175 176     #Draw Everything177         screen.blit(background, (0, 0))178         allsprites.draw(screen)179         pygame.display.flip()180 181 #Game Over182 183 184 #this calls the ‘main‘ function when this script is executed185 if __name__ == ‘__main__‘: main()

Source code download: http://files.cnblogs.com/liuzhi/spear_elephant.zip

Pygame series _ elephant game

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.