分享30个有趣的 Python小游戏,我能玩一天(附源码)
Posted 我爱Python数据挖掘
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分享30个有趣的 Python小游戏,我能玩一天(附源码)相关的知识,希望对你有一定的参考价值。
大家好,今天给大家带来30个 Python 小游戏,喜欢记得点赞、一定要收藏,完整版代码,文末获取
文章目录
有手就行
1、吃金币
【有手就行系列不介绍玩法了+附源码】
源码分享:
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption('catch coins —— 九歌')
for key, value in cfg.IMAGE_PATHS.items():
if isinstance(value, list):
for item in value: images.append(pygame.image.load(item))
game_images[key] = images
game_images[key] = pygame.image.load(value)
for key, value in cfg.AUDIO_PATHS.items():
if key == 'bgm': continue
game_sounds[key] = pygame.mixer.Sound(value)
return screen, game_images, game_sounds
screen, game_images, game_sounds = initGame()
pygame.mixer.music.load(cfg.AUDIO_PATHS['bgm'])
pygame.mixer.music.play(-1, 0.0)
font = pygame.font.Font(cfg.FONT_PATH, 40)
hero = Hero(game_images['hero'], position=(375, 520))
food_sprites_group = pygame.sprite.Group()
generate_food_freq = random.randint(10, 20)
generate_food_count = 0
highest_score = 0 if not os.path.exists(cfg.HIGHEST_SCORE_RECORD_FILEPATH) else int(open(cfg.HIGHEST_SCORE_RECORD_FILEPATH).read())
clock = pygame.time.Clock()
screen.blit(game_images['background'], (0, 0))
countdown_text = 'Count down: ' + str((90000 - pygame.time.get_ticks()) // 60000) + ":" + str((90000 - pygame.time.get_ticks()) // 1000 % 60).zfill(2)
countdown_text = font.render(countdown_text, True, (0, 0, 0))
countdown_rect = countdown_text.get_rect()
countdown_rect.topright = [cfg.SCREENSIZE[0]-30, 5]
screen.blit(countdown_text, countdown_rect)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_a] or key_pressed[pygame.K_LEFT]:
hero.move(cfg.SCREENSIZE, 'left')
if key_pressed[pygame.K_d] or key_pressed[pygame.K_RIGHT]:
hero.move(cfg.SCREENSIZE, 'right')
generate_food_count += 1
if generate_food_count > generate_food_freq:
generate_food_freq = random.randint(10, 20)
generate_food_count = 0
food = Food(game_images, random.choice(['gold',] * 10 + ['apple']), cfg.SCREENSIZE)
food_sprites_group.add(food)
for food in food_sprites_group:
if food.update(): food_sprites_group.remove(food)
for food in food_sprites_group:
if pygame.sprite.collide_mask(food, hero):
game_sounds['get'].play()
food_sprites_group.remove(food)
score += food.score
if score > highest_score: highest_score = score
hero.draw(screen)
food_sprites_group.draw(screen)
score_text = f'Score: score, Highest: highest_score'
score_text = font.render(score_text, True, (0, 0, 0))
score_rect = score_text.get_rect()
score_rect.topleft = [5, 5]
screen.blit(score_text, score_rect)
if pygame.time.get_ticks() >= 90000:
pygame.display.flip()
clock.tick(cfg.FPS)
# 游戏结束, 记录最高分并显示游戏结束画面
fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')
fp.write(str(highest_score))
return showEndGameInterface(screen, cfg, score, highest_score)
if __name__ == '__main__':
2、打乒乓
源码分享:
def Button(screen, position, text, button_size=(200, 50)):
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(cfg.FONTPATH, 30)
text_render = font.render(text, 1, (255, 235, 205))
return screen.blit(text_render, (left+50, top+10))
--game_mode: 1(单人模式)/2(双人模式)
def startInterface(screen):
clock = pygame.time.Clock()
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
pygame.display.update()
def endInterface(screen, score_left, score_right):
clock = pygame.time.Clock()
font1 = pygame.font.Font(cfg.FONTPATH, 30)
font2 = pygame.font.Font(cfg.FONTPATH, 20)
msg = 'Player on left won!' if score_left > score_right else 'Player on right won!'
texts = [font1.render(msg, True, cfg.WHITE),
font2.render('Press ESCAPE to quit.', True, cfg.WHITE),
font2.render('Press ENTER to continue or play again.', True, cfg.WHITE)]
positions = [[120, 200], [155, 270], [80, 300]]
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)
pygame.display.update()
hit_sound = pygame.mixer.Sound(cfg.HITSOUNDPATH)
goal_sound = pygame.mixer.Sound(cfg.GOALSOUNDPATH)
pygame.mixer.music.load(cfg.BGMPATH)
pygame.mixer.music.play(-1, 0.0)
font = pygame.font.Font(cfg.FONTPATH, 50)
game_mode = startInterface(screen)
# --左边球拍(ws控制, 仅双人模式时可控制)
racket_left = Racket(cfg.RACKETPICPATH, 'LEFT', cfg)
racket_right = Racket(cfg.RACKETPICPATH, 'RIGHT', cfg)
ball = Ball(cfg.BALLPICPATH, cfg)
clock = pygame.time.Clock()
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')
racket_left.automove(ball)
scores = ball.move(ball, racket_left, racket_right, hit_sound, goal_sound)
score_left += scores[0]
score_right += scores[1]
pygame.draw.rect(screen, cfg.WHITE, (247, 0, 6, 500))
ball.draw(screen)
racket_left.draw(screen)
racket_right.draw(screen)
screen.blit(font.render(str(score_left), False, cfg.WHITE), (150, 10))
screen.blit(font.render(str(score_right), False, cfg.WHITE), (300, 10))
if score_left == 11 or score_right == 11:
return score_left, score_right
pygame.display.update()
screen = pygame.display.set_mode((cfg.WIDTH, cfg.HEIGHT))
pygame.display.set_caption('pingpong —— 九歌')
score_left, score_right = runDemo(screen)
endInterface(screen, score_left, score_right)
if __name__ == '__main__':
3、滑雪
源码分享:
class SkierClass(pygame.sprite.Sprite):
pygame.sprite.Sprite.__init__(self)
self.direction = 0
self.imagepaths = cfg.SKIER_IMAGE_PATHS[:-1]
self.image = pygame.image.load(self.imagepaths[self.direction])
self.rect = self.image.get_rect()
self.rect.center = [320, 100]
self.speed = [self.direction, 6-abs(self.direction)*2]
'''改变滑雪者的朝向. 负数为向左,正数为向右,0为向前'''
self.direction += num
self.direction = max(-2, self.direction)
self.direction = min(2, self.direction)
center = self.rect.center
self.image = pygame.image.load(self.imagepaths[self.direction])
self.rect = self.image.get_rect()
self.rect.center = center
self.speed = [self.direction, 6-abs(self.direction)*2]
return self.speed
self.rect.centerx += self.speed[0]
self.rect.centerx = max(20, self.rect.centerx)
self.rect.centerx = min(620, self.rect.centerx)
self.image = pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])
def setForward(self):
self.direction = 0
self.image = pygame.image.load(self.imagepaths[self.direction])
class ObstacleClass(pygame.sprite.Sprite):
def __init__(self, img_path, location, attribute):
pygame.sprite.Sprite.__init__(self)
self.img_path = img_path
self.image = pygame.image.load(self.img_path)
self.location = location
self.rect = self.image.get_rect()
self.rect.center = self.location
self.attribute = attribute
self.passed = False
self.rect.centery = self.location[1] - num
def createObstacles(s, e, num=10):
obstacles = pygame.sprite.Group()
row = random.randint(s, e)
col = random.randint(0,以上是关于分享30个有趣的 Python小游戏,我能玩一天(附源码)的主要内容,如果未能解决你的问题,请参考以下文章