Preface:

Make a simple table tennis game using Python. Let’s have a good time

The development tools

Python version: 3.6.4

Related modules:

Pygame module;

And some modules that come with Python.

Environment set up

PIP installation requires related modules.

Results show

Introduction of the principle

Rules of the game:

Operation:

Player 1(right) moves the racket up and down by using the ↑↓ key;

Player 2(left) moves the racket up and down using the WS key (two-player only).

Score:

A player who does not catch the ball loses one point, which is one point for the opposing player. The first team to accumulate 11 points is the winner. The front row is 762, the middle row is 459, and the back row is 510. She will arrange to learn the three groups of letters together.

Step by step:

Step1: start interface

The start screen is as simple as defining two buttons and then passing the value of the buttons to the rest of the game’s main loop when it detects that the player has clicked on them. The code implementation is as follows:

Def Button(screen, position, text, button_size=(200, 50)): def Button(screen, position, text, button_size=(200, 50)) left, top = position bwidth, bheight = button_size pygame.draw.line(screen, (150, 150, 150), (left, top), (left+bwidth, top), 5) pygame.draw.line(screen, (150, 150, 150), (left, top-2), (left, top+bheight), 5) pygame.draw.line(screen, (50, 50, 50), (left, top+bheight), (left+bwidth, top+bheight), 5) pygame.draw.line(screen, (50, 50, 50), (left+bwidth, top+bheight), (left+bwidth, top), 5) pygame.draw.rect(screen, (100, 100, 100), (left, top, bwidth, bheight)) font = pygame.font.Font(config.FONTPATH, 30) text_render = font.render(text, 1, (255, 235, Blit (text_render, (left+50, top+10)) Function Input: --screen: 1(single player)/2(double player) "" def startInterface(screen): clock = pygame.time.clock () while True: screen.fill((41, 36, 33)) button_1 = Button(screen, (150, 175), '1 Player') button_2 = Button(screen, (150, 275), '2 Player') for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if button_1.collidepoint(pygame.mouse.get_pos()): return 1 elif button_2.collidepoint(pygame.mouse.get_pos()): return 2 clock.tick(10) pygame.display.update()Copy the code

Step2: Main loop of the game

Next, write the game’s main loop. For convenience, define two game sprites, namely racket Sprite and ball Sprite. Among them, the racket spirit should have the ability to be manually controlled and moved by the player/automatically controlled and moved by the computer according to the position of the table tennis, and the specific implementation is as follows:

Class Racket(pyGame.sprite): def __init__(self, imgPath, type_, **kwargs): pygame.sprite.Sprite.__init__(self) self.type_ = type_ self.image = loadImage(imgpath, False) self.rect = self.image.get_rect() self.reset() "def move(self, direction): if direction == 'UP': self.rect.top = max(0, self.rect.top-self.speed) elif direction == 'DOWN': self.rect.bottom = min(config.HEIGHT, self.rect.bottom+self.speed) else: raise ValueError('[direction] in Racket.move is <%s>, expect <%s> or <%s>... "Def automove(self, ball): if ball.rect.centery - 25 > self. Self.move ('DOWN') if ball.rect.centery + 25 < self.rect.centery: self.move('UP') "" def reset(self): Centerx = config.WIDTH-self. Rect. WIDTH //2 if self.type_ == 'RIGHT' else self.rect. WIDTH //2 Self.rect. centery = config.HEIGHT // 2 # speed = 5 "" def draw(self, screen): screen.blit(self.image, self.rect)Copy the code

Table tennis only needs to be based on the current situation (including whether to hit the wall, whether to hit the racket, etc.) automatically move. One thing to note is that in order to keep the game from going on indefinitely, the speed of the ping-pong ball increases **** + each time it hits the racket/wall. Specifically, the code implementation is as follows:

Class Ball(pygame.sprite.sprite): def __init__(self, imgPath, **kwargs): pygame.sprite.Sprite.__init__(self) self.image = loadImage(imgpath) self.rect = self.image.get_rect() self.reset() Def move(self, ball, racket_left, racket_right, hit_sound, goal_sound): self.rect.left = self.rect.left + self.speed * self.direction_x self.rect.top = min(max(self.rect.top+self.speed*self.direction_y, 0), Config.HEIGHT-self. Rect. HEIGHT) # if pygame.sprite. racket_left) or pygame.sprite.collide_rect(ball, racket_right): self.direction_x, self.direction_y = -self.direction_x, random.choice([1, -1]) self.speed += 1 scores = [0, 0] hit_sound.play() # elif self.rect.top == 0: Self. Direction_y = 1 self. Speed += 1 scores = [0, 0] # Self. rect.left < 0: self.rect.left < 0: self.rect.left < 0: self.rect.left < 0: self.rect.left < 0: self.rect.left < 0: self.reset() racket_left.reset() racket_right.reset() scores = [0, 1] goal_sound.play() # goal_sound.right > config.width: Self. reset() racket_left. Reset () racket_right. Reset () goal_sound.play() # Def reset(self) = 0, 0, 0) def reset(self): self.rect.centerx = config.WIDTH // 2 self.rect.centery = random.randrange(self.rect.height//2, config.HEIGHT-self.rect.height//2) self.direction_x = random.choice([1, -1]) self.direction_y = random.choice([1, Def draw(self, screen): screen.blit(self.image, self.rect) def draw(self, screen): screen.blit(self.Copy the code

With the two main sprites defined, we can start writing the main loop. The logic is simple. First, respond to player actions through keystroke detection; Then, update the game state in real time (ping-pong position, racket, etc.) based on the player’s actions; Finally, count the score and judge whether the game is over. If so, enter the end interface; otherwise, update the current game interface. Specifically, the code implementation is as follows:

while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(-1) screen.fill((41, 36, 33) # pressed_keys = pygame.key.get_pressed() if pressed_keys[pygame.k_up]: racket_right.move('UP') elif pressed_keys[pygame.K_DOWN]: racket_right.move('DOWN') if game_mode == 2: if pressed_keys[pygame.K_w]: racket_left.move('UP') elif pressed_keys[pygame.K_s]: racket_left.move('DOWN') else: Racket_left. Racove (ball) # racket_left, racket_right, hit_sound, Goal_sound) score_left += scores[0] score_right += scores[1] # 0, 6, 500)) # -- ball. Draw (screen) # -- racket_left. Draw (screen) racket_right screen.blit(font.render(str(score_left), False, config.WHITE), (150, 10)) screen.blit(font.render(str(score_right), False, config.WHITE), (300, 10)) if score_left == 11 or score_right == 11: return score_left, score_right clock.tick(100) pygame.display.update()Copy the code

Step3: game end interface

The game end screen works in much the same way as the game start screen, so let’s just put the code in:

Def endInterface(screen, score_left, score_right): clock = pygame.time.Clock() font1 = pygame.font.Font(config.FONTPATH, 30) font2 = pygame.font.Font(config.FONTPATH, 20) msg = 'Player on left won! ' if score_left > score_right else 'Player on right won! ' texts = [font1.render(msg, True, config.WHITE), font2.render('Press ESCAPE to quit.', True, config.WHITE), font2.render('Press ENTER to continue or play again.', True, config.WHITE)] positions = [[120, 200], [155, 270], [80, 300]] while True: screen.fill((41, 36, 33)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: return elif event.key == pygame.K_ESCAPE: sys.exit() pygame.quit() for text, pos in zip(texts, positions): screen.blit(text, pos) clock.tick(10) pygame.display.update()Copy the code

That’s the end of this article, thank you for watching, next article sharing brick breaking mini-games

To thank you readers, I’d like to share some of my recent programming favorites to give back to each and every one of you in the hope that they can help you. Finally, if your time is not very tight, and you want to improve Python quickly, the most important thing is not to be afraid of hardship, I suggest you to extend my pseudo xin 762459510, that is really good, many people progress quickly, need you not to be afraid of hardship! You can go to add a look at ~

Dry goods mainly include:

① Over 2000 Python ebooks (both mainstream and classic books should be available)

②Python Standard Library (Most Complete Chinese version)

③ project source code (forty or fifty interesting and classic practice projects and source code)

④Python basic introduction, crawler, Web development, big data analysis video (suitable for small white learning)

⑤ A Roadmap for Learning Python

⑥ Two days of Python crawler boot camp live access

All done~ see personal profile or private letter for complete source code.

If you do meet a good coworker, you’ll be lucky. Come on!

Include Python, PythonWeb, crawler, data analysis and other Python skills, as well as artificial intelligence, big data, data mining, automated office learning methods. Build from zero to the project development hands-on combat all-round analysis!