python中的乒乓球游戏.分数和屏幕外检查 [英] Pong game in python. Score and out-of-screen check

查看:101
本文介绍了python中的乒乓球游戏.分数和屏幕外检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上周我们进行了乒乓球比赛.

代码如下:

导入pygame屏幕宽度 = 800屏幕高度 = 600白色 = (255, 255, 255)黑色 = (0, 0, 0)类球:# свойстваdef __init__(self):self.rect = pygame.Rect(0, 0, 20, 20)self.rect.center = (SCREEN_WIDTH//2, SCREEN_HEIGHT//2)self.dx = 5 # скорость по иксуself.dy = 5 # скорость по игрекуself.game_over = 假# методыdef draw(self, screen):pygame.draw.circle(screen, WHITE, self.rect.center, 10) # 10 - радиус мяча定义移动(自我):x, y = self.rect.centerx += self.dxy += self.dyself.rect.center = (x, y)如果 y >SCREEN_HEIGHT 或 y <0:self.dy *= -1如果 x >SCREEN_WIDTH 或 x <0:#self.dx *= -1打印('游戏结束')self.game_over = 真类桨:#ракеткаdef __init__(self, x, y):self.rect = pygame.Rect(x, y, 10, 100)def draw(self, screen):pygame.draw.rect(屏幕,白色,self.rect)# ---------------- проверка на столкновение -------------------------- #def check_collision(球,桨):如果 ball.rect.colliderect(paddle.rect):球.dx *= -1# -------------------- управление ракетками ----------------------------#def control_human(桨):keys_pressed = pygame.key.get_pressed()如果keys_pressed[pygame.K_UP]:paddle.rect.y -= 5如果keys_pressed[pygame.K_DOWN]:paddle.rect.y += 5def control_computer(桨,球):# если мяч летит от компьютера, то ничего не делать如果 ball.dx <0:返回# если мяч выше ракетки, то двигаем ракетку вверх如果 ball.rect.y paddle.rect.y:paddle.rect.y += 5#if paddle.rect.y + 100 >屏幕高度:# paddle.rect.y = SCREEN_HEIGHT - 100如果 paddle.rect.bottom >屏幕高度:paddle.rect.bottom = SCREEN_HEIGHT# --------------------------------------------------------------------- #pygame.init()screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))# ---------------- создаем объекты для игры -------------------------- #球 = 球()left_paddle = Paddle(30, SCREEN_HEIGHT//2 - 50)right_paddle = Paddle(SCREEN_WIDTH - 40, SCREEN_HEIGHT//2 - 50)时钟 = pygame.time.Clock()font = pygame.font.SysFont("Lucida Console", 30)label = font.render("G A M E O V E R", 1, (255, 0, 0, 255))# -------------------- главный цикл игры ----------------------------- #为真:屏幕填充(黑色)对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:pygame.quit()如果不是 ball.game_over:球.移动()ball.draw(屏幕)control_human(left_paddle)control_computer(right_paddle,球)left_paddle.draw(屏幕)right_paddle.draw(屏幕)check_collision(球,left_paddle)check_collision(球,right_paddle)别的:screen.blit(label, (50, 100) )pygame.display.update()时钟滴答(60)

我们需要为人类球员的球拍添加屏幕外检查.为每个球员添加成功踢球的计数并在屏幕上显示当前得分.

解决方案

可以在 control_human 中完成人类桨的屏幕外检查".如果桨向上移动,则最终桨顶部位置为最大值(

导入pygame屏幕宽度 = 800屏幕高度 = 600白色 = (255, 255, 255)黑色 = (0, 0, 0)类球:# свойстваdef __init__(self):self.rect = pygame.Rect(0, 0, 20, 20)self.rect.center = (SCREEN_WIDTH//2, SCREEN_HEIGHT//2)self.dx = 5 # скорость по иксуself.dy = 5 # скорость по игрекуself.game_over = 假# методыdef draw(self, screen):pygame.draw.circle(screen, WHITE, self.rect.center, 10) # 10 - радиус мяча定义移动(自我):x, y = self.rect.centerx += self.dxy += self.dyself.rect.center = (x, y)如果 y >SCREEN_HEIGHT 或 y <0:self.dy *= -1如果 x >SCREEN_WIDTH 或 x <0:#self.dx *= -1打印('游戏结束')self.game_over = 真类桨:#ракеткаdef __init__(self, x, y):self.rect = pygame.Rect(x, y, 10, 100)def draw(self, screen):pygame.draw.rect(屏幕,白色,self.rect)# ---------------- проверка на столкновение -------------------------- #def check_collision(球,桨):如果 ball.rect.colliderect(paddle.rect):球.dx *= -1返回真返回错误# -------------------- управление ракетками ----------------------------#def control_human(桨):keys_pressed = pygame.key.get_pressed()如果keys_pressed[pygame.K_UP]:paddle.rect.top = max(0, paddle.rect.top - 5)如果keys_pressed[pygame.K_DOWN]:paddle.rect.bottom = min(SCREEN_HEIGHT, paddle.rect.bottom + 5)def control_computer(桨,球):# если мяч летит от компьютера, то ничего не делать如果 ball.dx <0:返回# если мяч выше ракетки, то двигаем ракетку вверх如果 ball.rect.y paddle.rect.y:paddle.rect.y += 5#if paddle.rect.y + 100 >屏幕高度:# paddle.rect.y = SCREEN_HEIGHT - 100如果 paddle.rect.bottom >屏幕高度:paddle.rect.bottom = SCREEN_HEIGHT# --------------------------------------------------------------------- #pygame.init()screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))# ---------------- создаем объекты для игры -------------------------- #球 = 球()left_paddle = Paddle(30, SCREEN_HEIGHT//2 - 50)right_paddle = Paddle(SCREEN_WIDTH - 40, SCREEN_HEIGHT//2 - 50)时钟 = pygame.time.Clock()font = pygame.font.SysFont("Lucida Console", 30)label = font.render("G A M E O V E R", 1, (255, 0, 0, 255))# -------------------- главный цикл игры ----------------------------- #分数 = 0为真:屏幕填充(黑色)对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:pygame.quit()如果不是 ball.game_over:球.移动()ball.draw(屏幕)control_human(left_paddle)control_computer(right_paddle,球)left_paddle.draw(屏幕)right_paddle.draw(屏幕)如果 check_collision(ball, left_paddle):得分 += 1打印(分数)check_collision(球,right_paddle)score_label = font.render(str(score), 1, (255, 0, 0, 255))screen.blit(score_label, (10, 10))别的:screen.blit(label, (50, 100) )pygame.display.update()时钟滴答(60)

Last week we did a pong game.

Here's the code:

import pygame

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

class Ball:
    # свойства
    def __init__(self):
        self.rect = pygame.Rect(0, 0, 20, 20)
        self.rect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
        self.dx = 5     # скорость по иксу
        self.dy = 5     # скорость по игреку
        self.game_over = False

    # методы
    def draw(self, screen):
        pygame.draw.circle(screen, WHITE, self.rect.center, 10)     # 10 - радиус мяча

    def move(self):
        x, y = self.rect.center
        x += self.dx
        y += self.dy
        self.rect.center = (x, y)
        if y > SCREEN_HEIGHT or y < 0:
            self.dy *= -1
        if x > SCREEN_WIDTH or x < 0:
            #self.dx *= -1
            print('Game Over')
            self.game_over = True          

class Paddle:   # ракетка
    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, 10, 100)

    def draw(self, screen):
        pygame.draw.rect(screen, WHITE, self.rect)

# ----------------  проверка на столкновение -------------------------- #

def check_collision(ball, paddle):
    if ball.rect.colliderect(paddle.rect):
        ball.dx *= -1

# -------------------- управление ракетками --------------------------- #

def control_human(paddle):
    keys_pressed = pygame.key.get_pressed()
    if keys_pressed[pygame.K_UP]:
        paddle.rect.y -= 5
    if keys_pressed[pygame.K_DOWN]:
        paddle.rect.y += 5

def control_computer(paddle, ball):
    # если мяч летит от компьютера, то ничего не делать
    if ball.dx < 0:
        return
    # если мяч выше ракетки, то двигаем ракетку вверх
    if ball.rect.y < paddle.rect.y:
        paddle.rect.y -= 5
        if paddle.rect.y < 0:
            paddle.rect.y = 0
    # если мяч ниже ракетки, то двигаем ракетку вниз
    if ball.rect.y > paddle.rect.y:
        paddle.rect.y += 5
        #if paddle.rect.y + 100 > SCREEN_HEIGHT:
        #    paddle.rect.y = SCREEN_HEIGHT - 100
        if paddle.rect.bottom > SCREEN_HEIGHT:
            paddle.rect.bottom = SCREEN_HEIGHT    

# --------------------------------------------------------------------- #
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# ----------------  создаем объекты для игры -------------------------- #

ball = Ball()
left_paddle = Paddle(30, SCREEN_HEIGHT // 2 - 50)
right_paddle = Paddle(SCREEN_WIDTH - 40, SCREEN_HEIGHT // 2 - 50)
clock = pygame.time.Clock()
font = pygame.font.SysFont("Lucida Console", 30)
label = font.render("G A M E   O V E R", 1, (255, 0, 0, 255))

# --------------------  главный цикл игры ----------------------------- #
while True:
    screen.fill(BLACK)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    if not ball.game_over:
        ball.move()
        ball.draw(screen)
        control_human(left_paddle)
        control_computer(right_paddle, ball)
        left_paddle.draw(screen)
        right_paddle.draw(screen)
        check_collision(ball, left_paddle)
        check_collision(ball, right_paddle)
    else:
        screen.blit(label, (50, 100) )
    pygame.display.update()
    clock.tick(60)

We need to add an out-of-screen check on the human player's racket. Add counting of successful kicks to the ball for each player and display the current score on the screen.

解决方案

The "out-of-screen check" of the human paddle can be done in control_human. If the paddle is moved up, the final paddle top position is the maximum (max) of 0 and paddle.rect.top-5. If the paddle is moved down, then the final paddle bottom position is the minimum (min) of SCREEN_HEIGHT and paddle.rect.bottom+5:

def control_human(paddle):
    keys_pressed = pygame.key.get_pressed()
    if keys_pressed[pygame.K_UP]:
        paddle.rect.top = max(0, paddle.rect.top - 5)
    if keys_pressed[pygame.K_DOWN]:
        paddle.rect.bottom = min(SCREEN_HEIGHT, paddle.rect.bottom + 5)


To count the score add a return value to the function check_collision. The function has to return True if the ball collides with the paddle. Else the function returns False:

def check_collision(ball, paddle):
    if ball.rect.colliderect(paddle.rect):
        ball.dx *= -1
        return True
    return False

Add a score and increment the score if left_paddle collides with ball. Convert the score to a string by str, render the string and blit it to the display:

score = 0
while True:
    # [...]

    if not ball.game_over:
        ball.move()
        ball.draw(screen)
        control_human(left_paddle)
        control_computer(right_paddle, ball)
        left_paddle.draw(screen)
        right_paddle.draw(screen)

        if check_collision(ball, left_paddle):
            score += 1

        check_collision(ball, right_paddle)

        score_label = font.render(str(score), 1, (255, 0, 0, 255))
        screen.blit(score_label, (10, 10))

    else:
        screen.blit(label, (50, 100) )

    # [...]


Complete example:

import pygame

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

class Ball:
    # свойства
    def __init__(self):
        self.rect = pygame.Rect(0, 0, 20, 20)
        self.rect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
        self.dx = 5     # скорость по иксу
        self.dy = 5     # скорость по игреку
        self.game_over = False

    # методы
    def draw(self, screen):
        pygame.draw.circle(screen, WHITE, self.rect.center, 10)     # 10 - радиус мяча

    def move(self):
        x, y = self.rect.center
        x += self.dx
        y += self.dy
        self.rect.center = (x, y)
        if y > SCREEN_HEIGHT or y < 0:
            self.dy *= -1
        if x > SCREEN_WIDTH or x < 0:
            #self.dx *= -1
            print('Game Over')
            self.game_over = True          

class Paddle:   # ракетка
    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, 10, 100)

    def draw(self, screen):
        pygame.draw.rect(screen, WHITE, self.rect)

# ----------------  проверка на столкновение -------------------------- #

def check_collision(ball, paddle):
    if ball.rect.colliderect(paddle.rect):
        ball.dx *= -1
        return True
    return False

# -------------------- управление ракетками --------------------------- #

def control_human(paddle):
    keys_pressed = pygame.key.get_pressed()
    if keys_pressed[pygame.K_UP]:
        paddle.rect.top = max(0, paddle.rect.top - 5)
    if keys_pressed[pygame.K_DOWN]:
        paddle.rect.bottom = min(SCREEN_HEIGHT, paddle.rect.bottom + 5)

def control_computer(paddle, ball):
    # если мяч летит от компьютера, то ничего не делать
    if ball.dx < 0:
        return
    # если мяч выше ракетки, то двигаем ракетку вверх
    if ball.rect.y < paddle.rect.y:
        paddle.rect.y -= 5
        if paddle.rect.y < 0:
            paddle.rect.y = 0
    # если мяч ниже ракетки, то двигаем ракетку вниз
    if ball.rect.y > paddle.rect.y:
        paddle.rect.y += 5
        #if paddle.rect.y + 100 > SCREEN_HEIGHT:
        #    paddle.rect.y = SCREEN_HEIGHT - 100
        if paddle.rect.bottom > SCREEN_HEIGHT:
            paddle.rect.bottom = SCREEN_HEIGHT    

# --------------------------------------------------------------------- #
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

# ----------------  создаем объекты для игры -------------------------- #

ball = Ball()
left_paddle = Paddle(30, SCREEN_HEIGHT // 2 - 50)
right_paddle = Paddle(SCREEN_WIDTH - 40, SCREEN_HEIGHT // 2 - 50)
clock = pygame.time.Clock()
font = pygame.font.SysFont("Lucida Console", 30)
label = font.render("G A M E   O V E R", 1, (255, 0, 0, 255))

# --------------------  главный цикл игры ----------------------------- #
score = 0
while True:
    screen.fill(BLACK)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    if not ball.game_over:
        ball.move()
        ball.draw(screen)
        control_human(left_paddle)
        control_computer(right_paddle, ball)
        left_paddle.draw(screen)
        right_paddle.draw(screen)
        if check_collision(ball, left_paddle):
            score += 1
            print(score)
        check_collision(ball, right_paddle)
        score_label = font.render(str(score), 1, (255, 0, 0, 255))
        screen.blit(score_label, (10, 10))
    else:
        screen.blit(label, (50, 100) )

    pygame.display.update()
    clock.tick(60)

这篇关于python中的乒乓球游戏.分数和屏幕外检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆