本文主要是介绍用python制作小游戏,带你回到童年,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
想学Python的小伙伴可以关注小编
有很多的资源可以白嫖的哈,不定时会更新一下Python的小知识的哈!!
一、接金币
普通难度:❤
玩法介绍:吃金币,控制左右键,有手就行。
import os
import cfg
import sys
import pygame
import random
from modules import *'''游戏初始化''' python交流群309025914
def initGame():# 初始化pygame, 设置展示窗口 pygame.init()screen = pygame.display.set_mode(cfg.SCREENSIZE)pygame.display.set_caption('catch coins —— ')# 加载必要的游戏素材game_images = {}for key, value in cfg.IMAGE_PATHS.items():if isinstance(value, list):images = []for item in value: images.append(pygame.image.load(item))game_images[key] = imageselse:game_images[key] = pygame.image.load(value)game_sounds = {}for key, value in cfg.AUDIO_PATHS.items():if key == 'bgm': continuegame_sounds[key] = pygame.mixer.Sound(value)# 返回初始化数据return screen, game_images, game_sounds'''主函数'''
def main():# 初始化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)# 定义herohero = Hero(game_images['hero'], position=(375, 520))# 定义食物组food_sprites_group = sprite.group -()generate_food_freq = random.randint(10, 20)generate_food_count = 0# 当前分数/历史最高分score = 0highest_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()while True:# --填充背景screen.fill(0)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 += 1if generate_food_count > generate_food_freq:generate_food_freq = random.randint(10, 20)generate_food_count = 0food = 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.scoreif score > highest_score: highest_score = score# --画herohero.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:break# --更新屏幕pygame.display.flip()clock.tick(cfg.FPS)# 游戏结束, 记录最高分并显示游戏结束画面fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')fp.write(str(highest_score))fp.close()return showEndGameInterface(screen, cfg, score, highest_score)'''run'''
if __name__ == '__main__':while main():pass
二.俄罗斯方块
困难难度:❤❤
玩法介绍:小时候的经典游戏,加速玩法有一点点难度。
import os
import sys
import random
from modules import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *'''定义俄罗斯方块游戏类'''
class TetrisGame(QMainWindow):def __init__(self, parent=None):super(TetrisGame, self).__init__(parent)# 是否暂停ingself.is_paused = False# 是否开始ingself.is_started = Falseself.initUI()'''界面初始化'''def initUI(self):# iconself.setWindowIcon(QIcon(os.path.join(os.getcwd(), 'resources/icon.jpg')))# 块大小self.grid_size = 22# 游戏帧率self.fps = 200self.timer = QBasicTimer()# 焦点self.setFocusPolicy(Qt.StrongFocus)# 水平布局layout_horizontal = QHBoxLayout()self.inner_board = InnerBoard()self.external_board = ExternalBoard(self, self.grid_size, self.inner_board)layout_horizontal.addWidget(self.external_board)self.side_panel = SidePanel(self, self.grid_size, self.inner_board)layout_horizontal.addWidget(self.side_panel)self.status_bar = self.statusBar()self.external_board.score_signal[str].connect(self.status_bar.showMessage)self.start()self.center()self.setWindowTitle('Tetris —— 九歌')self.show()self.setFixedSize(self.external_board.width() + self.side_panel.width(), self.side_panel.height() + self.status_bar.height())'''游戏界面移动到屏幕中间'''def center(self):screen = QDesktopWidget().screenGeometry()size = self.geometry()self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)'''更新界面'''def updateWindow(self):self.external_board.updateData()self.side_panel.updateData()self.update()'''开始'''def start(self):if self.is_started:returnself.is_started = Trueself.inner_board.createNewTetris()self.timer.start(self.fps, self)'''暂停/不暂停'''def pause(self):if not self.is_started:returnself.is_paused = not self.is_pausedif self.is_paused:self.timer.stop()self.external_board.score_signal.emit('Paused')else:self.timer.start(self.fps, self)self.updateWindow()'''计时器事件'''def timerEvent(self, event):if event.timerId() == self.timer.timerId():removed_lines = self.inner_board.moveDown()self.external_board.score += removed_linesself.updateWindow()else:super(TetrisGame, self).timerEvent(event)'''按键事件'''def keyPressEvent(self, event):if not self.is_started or self.inner_board.current_tetris == tetrisShape().shape_empty:super(TetrisGame, self).keyPressEvent(event)returnkey = event.key()# P键暂停if key == Qt.Key_P:self.pause()returnif self.is_paused:return# 向左elif key == Qt.Key_Left:self.inner_board.moveLeft()# 向右elif key == Qt.Key_Right:self.inner_board.moveRight()# 旋转elif key == Qt.Key_Up:self.inner_board.rotateAnticlockwise()# 快速坠落elif key == Qt.Key_Space:self.external_board.score += self.inner_board.dropDown()else:super(TetrisGame, self).keyPressEvent(event)self.updateWindow()'''run'''
if __name__ == '__main__':app = QApplication([])tetris = TetrisGame()sys.exit(app.exec_())
三、消消乐
困难难度:❤❤
玩法介绍:以前经典的游戏,给我感觉趣味性少了点
import os
import sys
import cfg
import pygame
from modules import *'''游戏主程序''' python交流群309025914
def main():pygame.init()screen = pygame.display.set_mode(cfg.SCREENSIZE)pygame.display.set_caption# 加载背景音乐pygame.mixer.init()pygame.mixer.music.load(os.path.join(cfg.ROOTDIR, "resources/audios/bg.mp3"))pygame.mixer.music.set_volume(0.6)pygame.mixer.music.play(-1)# 加载音效sounds = {}sounds['mismatch'] = pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/badswap.wav'))sounds['match'] = []for i in range(6):sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/match%s.wav' % i)))# 加载字体font = pygame.font.Font(os.path.join(cfg.ROOTDIR, 'resources/font/font.TTF'), 25)# 图片加载gem_imgs = []for i in range(1, 8):gem_imgs.append(os.path.join(cfg.ROOTDIR, 'resources/images/gem%s.png' % i))# 主循环game = gemGame(screen, sounds, font, gem_imgs, cfg)while True:score = game.start()flag = False# 一轮游戏结束后玩家选择重玩或者退出while True:for event in pygame.event.get():if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):pygame.quit()sys.exit()elif event.type == pygame.KEYUP and event.key == pygame.K_r:flag = Trueif flag:breakscreen.fill((135, 206, 235))text0 = 'Final score: %s' % scoretext1 = 'Press <R> to restart the game.'text2 = 'Press <Esc> to quit the game.'y = 150for idx, text in enumerate([text0, text1, text2]):text_render = font.render(text, 1, (85, 65, 0))rect = text_render.get_rect()if idx == 0:rect.left, rect.top = (212, y)elif idx == 1:rect.left, rect.top = (122.5, y)else:rect.left, rect.top = (126.5, y)y += 100screen.blit(text_render, rect)pygame.display.update()game.reset()'''run'''
if __name__ == '__main__':main()
这篇关于用python制作小游戏,带你回到童年的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!