이 블로그에서는 Pygame 라이브러리를 사용하여 게임 창을 만들고 게임 로직을 처리합니다.
1. 코드에 대한 자세한 설명:
먼저, pygame.init()
다음을 호출하여 Pygame 라이브러리를 초기화합니다.
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ball")
여기서의 WIDTH
합은 HEIGHT
창의 너비와 높이입니다.
다음으로, 함수를 호출하여 공, 폴, 점수의 이미지와 해당 위치를 초기화합니다 init_item
.
ball, ball_rect = init_item('bar.gif', random.randint(50, WIDTH - 50), 0)
bar, bar_rect = init_item('ball.jpg', 200, 400)
txt_score, txt_score_rect = show_text("Score:0", 40, 20, 20)
init_item
이 함수는 이미지 파일을 로드하고 이미지 객체와 직사각형 객체를 반환하는 데 사용되며, 직사각형 객체는 이미지의 위치를 제어하는 데 사용됩니다.
그런 다음 공의 초기 속도를 설정하고, 배경 음악을 재생하고, 타이머 개체와 점수 변수를 만듭니다.
ball_speed = [5, 5]
pygame.mixer.music.load('背景音乐.mp3')
pygame.mixer.music.play(loops=-1)
clock = pygame.time.Clock()
score = 0
ball_speed
수평 및 수직 방향의 공의 속도를 나타냅니다.
pygame.event.get()
다음은 사용자 입력 이벤트를 획득하고 처리하기 위해 호출되는 게임의 메인 루프입니다 . 예를 들어, 주요 이벤트를 확인하여 기둥의 움직임을 제어합니다.
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
# 左移杆子
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
# 右移杆子
if event.type == pygame.MOUSEBUTTONDOWN:
# 处理鼠标点击事件
사용자가 창의 닫기 버튼을 클릭하면 exit()
게임을 종료하는 함수가 호출됩니다.
그런 다음 공의 위치를 업데이트하고 공과 경계 사이의 충돌 및 공과 폴 사이의 충돌을 처리합니다.
ball_rect = ball_rect.move(ball_speed)
# 处理小球与边界的碰撞
if ball_rect.top < 0:
ball_speed[1] = -ball_speed[1]
if ball_rect.right > WIDTH or ball_rect.left < 0:
ball_speed[0] = -ball_speed[0]
# 处理小球与杆子的碰撞
if ball_rect.bottom > bar_rect.top and ball_rect.left > bar_rect.left and ball_rect.right < bar_rect.right:
# 碰到杆子,反弹并增加分数
ball_speed[1] = -ball_speed[1]
score += 1
공이 위쪽 및 아래쪽 경계에 닿으면 수직 속도가 반전되어 바운드되고, 왼쪽 및 오른쪽 경계에 닿으면 수평 속도가 반전됩니다. 공이 폴에 충돌하면 수직 속도가 반전되어 공이 튕겨져 점수가 높아집니다.
그런 다음 게임 상태에 따라 창의 내용을 업데이트합니다.
screen.fill((0, 0, 0)) # 清空窗口
if ball_rect.bottom > HEIGHT:
# 游戏结束,显示游戏结束的界面
else:
# 游戏未结束,显示小球、杆子和分数
공이 창 하단을 초과하면 게임이 종료되고 게임 종료 인터페이스가 표시됩니다. 그렇지 않으면 공, 폴, 점수가 표시됩니다.
2. 완전한 코드 표시:
import pygame
import random
WIDTH = 640
HEIGHT = 480
def mainGame():
# 显示窗口
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ball")
##球:
ball, ball_rect = init_item('bar.gif', random.randint(50, WIDTH - 50), 0)
##杆子
bar, bar_rect = init_item('ball.jpg', 200, 400)
##显示分数
txt_score, txt_score_rect = show_text("Score:0", 40, 20, 20)
ball_speed = [5, 5] ##小球的运行速度
pygame.mixer.music.load('背景音乐.mp3') # 导入音乐
pygame.mixer.music.play(loops=-1) # 循环播放
clock = pygame.time.Clock() ##用来设定窗口的刷新频率
##记分的变量
score = 0
while True:
clock.tick(60) ##每秒执行60次
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
if bar_rect.left > 3:
bar_rect = bar_rect.move([-80, 0])
else:
bar_rect = bar_rect.move([0, 0])
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
if bar_rect.right < WIDTH - 3:
bar_rect = bar_rect.move([80, 0])
else:
bar_rect = bar_rect.move([0, 0])
if event.type == pygame.MOUSEBUTTONDOWN:
if 250 <= event.pos[0] < 350 \
and 280 < event.pos[1] < 320:
mainGame()
ball_rect = ball_rect.move(ball_speed) ##球运动
if ball_rect.top < 0: ##遇到上下边界反弹
ball_speed[1] = -ball_speed[1]
if ball_rect.right > WIDTH or ball_rect.left < 0: ##遇到左右边界反弹
ball_speed[0] = -ball_speed[0]
##球和杆子的位置关系
if ball_rect.bottom > bar_rect.top \
and ball_rect.left > bar_rect.left \
and ball_rect.right < bar_rect.right: ##碰到杆子
ball_speed[1] = -ball_speed[1]
score += 1
# 游戏增加难度
if score % 5 == 0:
ball_speed[1] *= 1.2
ball_speed[0] *= 1.2
txt_score, txt_score_rect = show_text("Score:" + str(score), 40, 20, 20)
screen.fill((0, 0, 0)) ##把球停留过的位置颜色涂成黑色
if ball_rect.bottom > HEIGHT: ##本次游戏结束的条件
ball_speed = [0, 0]
over, over_rect = init_item('game over.jpg', 0, 0)
txt_score_over, txt_score_rect_over = show_text("Score:" + str(score), screen.get_rect().centerx,
screen.get_rect().centery, 48)
txt_restart, txt_restart_rect = show_text("Restart", 300, 300, 32)
screen.blit(over, over_rect) ##显示gameover图片
screen.blit(txt_score_over, txt_score_rect_over) ##结束的最终分数
screen.blit(txt_restart, txt_restart_rect) ##将分数显示在窗口左上脚
else:
screen.blit(ball, ball_rect) ##把球显示在窗口中
screen.blit(bar, bar_rect) ##把杆子显示在窗口中
screen.blit(txt_score, txt_score_rect) ##将分数显示在窗口左上脚
pygame.display.flip()
def show_text(txt, pos_x, pos_y, fontsize=12):
##设定显示文本信息
font = pygame.font.Font(None, fontsize)
text = font.render(txt, True, (255, 0, 0))
text_rect = text.get_rect()
text_rect.centerx = pos_x
text_rect.centery = pos_y
return text, text_rect
def init_item(img_path, pos_x, pos_y):
##显示图片
item = pygame.image.load(img_path)
item_rect = pygame.Rect((pos_x, pos_y, 0, 0))
item_rect.size = item.get_size()
return item, item_rect
if __name__ == "__main__":
mainGame()