假期玩嗨了吧,我給你準備了六個小游戲,有膽子來玩一玩嗎?我自己是玩了很多遍的,所以想讓大家一起玩,獨樂樂不如眾樂樂。代碼放在下麵。 1、小恐龍 玩法:上下控制起跳躲避 源碼分享: Python學習交流Q群:906715085### import cfg import sys import rando ...
假期玩嗨了吧,我給你準備了六個小游戲,有膽子來玩一玩嗎?我自己是玩了很多遍的,所以想讓大家一起玩,獨樂樂不如眾樂樂。代碼放在下麵。
1、小恐龍
玩法:上下控制起跳躲避
源碼分享:
Python學習交流Q群:906715085### import cfg import sys import random import pygame from modules import * '''main''' def main(highest_score): # 游戲初始化 pygame.init() screen = pygame.display.set_mode(cfg.SCREENSIZE) pygame.display.set_caption('九歌') # 導入所有聲音文件 sounds = {} for key, value in cfg.AUDIO_PATHS.items(): sounds[key] = pygame.mixer.Sound(value) # 游戲開始界面 GameStartInterface(screen, sounds, cfg) # 定義一些游戲中必要的元素和變數 score = 0 score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(534, 15), bg_color=cfg.BACKGROUND_COLOR) highest_score = highest_score highest_score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(435, 15), bg_color=cfg.BACKGROUND_COLOR, is_highest=True) dino = Dinosaur(cfg.IMAGE_PATHS['dino']) ground = Ground(cfg.IMAGE_PATHS['ground'], position=(0, cfg.SCREENSIZE[1])) cloud_sprites_group = pygame.sprite.Group() cactus_sprites_group = pygame.sprite.Group() ptera_sprites_group = pygame.sprite.Group() add_obstacle_timer = 0 score_timer = 0 # 游戲主迴圈 clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE or event.key == pygame.K_UP: dino.jump(sounds) elif event.key == pygame.K_DOWN: dino.duck() elif event.type == pygame.KEYUP and event.key == pygame.K_DOWN: dino.unduck() screen.fill(cfg.BACKGROUND_COLOR) # --隨機添加雲 if len(cloud_sprites_group) < 5 and random.randrange(0, 300) == 10: cloud_sprites_group.add(Cloud(cfg.IMAGE_PATHS['cloud'], position=(cfg.SCREENSIZE[0], random.randrange(30, 75)))) # --隨機添加仙人掌/飛龍 add_obstacle_timer += 1 if add_obstacle_timer > random.randrange(50, 150): add_obstacle_timer = 0 random_value = random.randrange(0, 10) if random_value >= 5 and random_value <= 7: cactus_sprites_group.add(Cactus(cfg.IMAGE_PATHS['cacti'])) else: position_ys = [cfg.SCREENSIZE[1]*0.82, cfg.SCREENSIZE[1]*0.75, cfg.SCREENSIZE[1]*0.60, cfg.SCREENSIZE[1]*0.20] ptera_sprites_group.add(Ptera(cfg.IMAGE_PATHS['ptera'], position=(600, random.choice(position_ys)))) # --更新游戲元素 dino.update() ground.update() cloud_sprites_group.update() cactus_sprites_group.update() ptera_sprites_group.update() score_timer += 1 if score_timer > (cfg.FPS//12): score_timer = 0 score += 1 score = min(score, 99999) if score > highest_score: highest_score = score if score % 100 == 0: sounds['point'].play() if score % 1000 == 0: ground.speed -= 1 for item in cloud_sprites_group: item.speed -= 1 for item in cactus_sprites_group: item.speed -= 1 for item in ptera_sprites_group: item.speed -= 1 # --碰撞檢測 for item in cactus_sprites_group: if pygame.sprite.collide_mask(dino, item): dino.die(sounds) for item in ptera_sprites_group: if pygame.sprite.collide_mask(dino, item): dino.die(sounds) # --將游戲元素畫到屏幕上 dino.draw(screen) ground.draw(screen) cloud_sprites_group.draw(screen) cactus_sprites_group.draw(screen) ptera_sprites_group.draw(screen) score_board.set(score) highest_score_board.set(highest_score) score_board.draw(screen) highest_score_board.draw(screen) # --更新屏幕 pygame.display.update() clock.tick(cfg.FPS) # --游戲是否結束 if dino.is_dead: break # 游戲結束界面 return GameEndInterface(screen, cfg), highest_score '''run''' if __name__ == '__main__': highest_score = 0 while True: flag, highest_score = main(highest_score) if not flag: break
2、消消樂
玩法:三個相連就能消除
源碼分享:
import os import sys import cfg import pygame from modules import * '''游戲主程式''' def main(): pygame.init() screen = pygame.display.set_mode(cfg.SCREENSIZE) pygame.display.set_caption('Gemgem —— 九歌') # 載入背景音樂 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 = True if flag: break screen.fill((135, 206, 235)) text0 = 'Final score: %s' % score text1 = 'Press <R> to restart the game.' text2 = 'Press <Esc> to quit the game.' y = 150 for 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 += 100 screen.blit(text_render, rect) pygame.display.update() game.reset() '''run''' if __name__ == '__main__': main()
3、俄羅斯方塊
玩法:童年經典,普通模式沒啥意思,小時候我們都是玩加速的。
源碼分享:
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) # 是否暫停ing self.is_paused = False # 是否開始ing self.is_started = False self.initUI() '''界面初始化''' def initUI(self): # icon self.setWindowIcon(QIcon(os.path.join(os.getcwd(), 'resources/icon.jpg'))) # 塊大小 self.grid_size = 22 # 游戲幀率 self.fps = 200 self.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: return self.is_started = True self.inner_board.createNewTetris() self.timer.start(self.fps, self) '''暫停/不暫停''' def pause(self): if not self.is_started: return self.is_paused = not self.is_paused if 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_lines self.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) return key = event.key() # P鍵暫停 if key == Qt.Key_P: self.pause() return if 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_())
4、貪吃蛇
玩法:童年經典,普通魔術也沒啥意思,小時候玩的也是加速的。
源碼分享:
import cfg import sys import pygame from modules import * '''主函數''' def main(cfg): # 游戲初始化 pygame.init() screen = pygame.display.set_mode(cfg.SCREENSIZE) pygame.display.set_caption('Greedy Snake —— 九歌') clock = pygame.time.Clock() # 播放背景音樂 pygame.mixer.music.load(cfg.BGMPATH) pygame.mixer.music.play(-1) # 游戲主迴圈 snake = Snake(cfg) apple = Apple(cfg, snake.coords) score = 0 while True: screen.fill(cfg.BLACK) # --按鍵檢測 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key in [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]: snake.setDirection({pygame.K_UP: 'up', pygame.K_DOWN: 'down', pygame.K_LEFT: 'left', pygame.K_RIGHT: 'right'}[event.key]) # --更新貪吃蛇和食物 if snake.update(apple): apple = Apple(cfg, snake.coords) score += 1 # --判斷游戲是否結束 if snake.isgameover: break # --顯示游戲里必要的元素 drawGameGrid(cfg, screen) snake.draw(screen) apple.draw(screen) showScore(cfg, score, screen) # --屏幕更新 pygame.display.update() clock.tick(cfg.FPS) return endInterface(screen, cfg) '''run''' if __name__ == '__main__': while True: if not main(cfg): break
5、24點小游戲
玩法:通過加減乘除操作,小學生都沒問題的。
源碼分享:
6、平衡木
玩法:也是小時候的經典
import os import sys import pygame from cfg import * from modules import * from fractions import Fraction '''檢查控制項是否被點擊''' def checkClicked(group, mouse_pos, group_type='NUMBER'): selected = [] # 數字卡片/運算符卡片 if group_type == GROUPTYPES[0] or group_type == GROUPTYPES[1]: max_selected = 2 if group_type == GROUPTYPES[0] else 1 num_selected = 0 for each in group: num_selected += int(each.is_selected) for each in group: if each.rect.collidepoint(mouse_pos): if each.is_selected: each.is_selected = not each.is_selected num_selected -= 1 each.select_order = None else: if num_selected < max_selected: each.is_selected = not each.is_selected num_selected += 1 each.select_order = str(num_selected) if each.is_selected: selected.append(each.attribute) # 按鈕卡片 elif group_type == GROUPTYPES[2]: for each in group: if each.rect.collidepoint(mouse_pos): each.is_selected = True selected.append(each.attribute) # 拋出異常 else: raise ValueError('checkClicked.group_type unsupport %s, expect %s, %s or %s...' % (group_type, *GROUPTYPES)) return selected '''獲取數字精靈組''' def getNumberSpritesGroup(numbers): number_sprites_group = pygame.sprite.Group() for idx, number in enumerate(numbers): args = (*NUMBERCARD_POSITIONS[idx], str(number), NUMBERFONT, NUMBERFONT_COLORS, NUMBERCARD_COLORS, str(number)) number_sprites_group.add(Card(*args)) return number_sprites_group '''獲取運算符精靈組''' def getOperatorSpritesGroup(operators): operator_sprites_group = pygame.sprite.Group() for idx, operator in enumerate(operators): args = (*OPERATORCARD_POSITIONS[idx], str(operator), OPERATORFONT, OPREATORFONT_COLORS, OPERATORCARD_COLORS, str(operator)) operator_sprites_group.add(Card(*args)) return operator_sprites_group '''獲取按鈕精靈組''' def getButtonSpritesGroup(buttons): button_sprites_group = pygame.sprite.Group() for idx, button in enumerate(buttons): args = (*BUTTONCARD_POSITIONS[idx], str(button), BUTTONFONT, BUTTONFONT_COLORS, BUTTONCARD_COLORS, str(button)) button_sprites_group.add(Button(*args)) return button_sprites_group '''計算''' def calculate(number1, number2, operator): operator_map = {'+': '+', '-': '-', '×': '*', '÷': '/'} try: result = str(eval(number1+operator_map[operator]+number2)) return result if '.' not in result else str(Fraction(number1+operator_map[operator]+number2)) except: return None '''在屏幕上顯示信息''' def showInfo(text, screen): rect = pygame.Rect(200, 180, 400, 200) pygame.draw.rect(screen, PAPAYAWHIP, rect) font = pygame.font.Font(FONTPATH, 40) text_render = font.render(text, True, BLACK) font_size = font.size(text) screen.blit(text_render, (rect.x+(rect.width-font_size[0])/2, rect.y+(rect.height-font_size[1])/2)) '''主函數''' def main(): # 初始化, 導入必要的游戲素材 pygame.init() pygame.mixer.init() screen = pygame.display.set_mode(SCREENSIZE) pygame.display.set_caption('24 point —— 九歌') win_sound = pygame.mixer.Sound(AUDIOWINPATH) lose_sound = pygame.mixer.Sound(AUDIOLOSEPATH) warn_sound = pygame.mixer.Sound(AUDIOWARNPATH) pygame.mixer.music.load(BGMPATH) pygame.mixer.music.play(-1, 0.0) # 24點游戲生成器 game24_gen = game24Generator() game24_gen.generate() # 精靈組 # --數字 number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now) # --運算符 operator_sprites_group = getOperatorSpritesGroup(OPREATORS) # --按鈕 button_sprites_group = getButtonSpritesGroup(BUTTONS) # 游戲主迴圈 clock = pygame.time.Clock() selected_numbers = [] selected_operators = [] selected_buttons = [] is_win = False while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(-1) elif event.type == pygame.MOUSEBUTTONUP: mouse_pos = pygame.mouse.get_pos() selected_numbers = checkClicked(number_sprites_group, mouse_pos, 'NUMBER') selected_operators = checkClicked(operator_sprites_group, mouse_pos, 'OPREATOR') selected_buttons = checkClicked(button_sprites_group, mouse_pos, 'BUTTON') screen.fill(AZURE) # 更新數字 if len(selected_numbers) == 2 and len(selected_operators) == 1: noselected_numbers = [] for each in number_sprites_group: if each.is_selected: if each.select_order == '1': selected_number1 = each.attribute elif each.select_order == '2': selected_number2 = each.attribute else: raise ValueError('Unknow select_order %s, expect 1 or 2...' % each.select_order) else: noselected_numbers.append(each.attribute) each.is_selected = False for each in operator_sprites_group: each.is_selected = False result = calculate(selected_number1, selected_number2, *selected_operators) if result is not None: game24_gen.numbers_now = noselected_numbers + [result] is_win = game24_gen.check() if is_win: win_sound.play() if not is_win and len(game24_gen.numbers_now) == 1: lose_sound.play() else: warn_sound.play() selected_numbers = [] selected_operators = [] number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now) # 精靈都畫到screen上 for each in number_sprites_group: each.draw(screen, pygame.mouse.get_pos()) for each in operator_sprites_group: each.draw(screen, pygame.mouse.get_pos()) for each in button_sprites_group: if selected_buttons and selected_buttons[0] in ['RESET', 'NEXT']: is_win = False if selected_buttons and each.attribute == selected_buttons[0]: each.is_selected = False number_sprites_group = each.do(game24_gen, getNumberSpritesGroup, number_sprites_group, button_sprites_group) selected_buttons = [] each.draw(screen, pygame.mouse.get_pos()) # 游戲勝利 if is_win: showInfo('Congratulations', screen) # 游戲失敗 if not is_win and len(game24_gen.numbers_now) == 1: showInfo('Game Over', screen) pygame.display.flip() clock.tick(30) '''run''' if __name__ == '__main__': main()
,控制左右就行,到後面才有一點點難度。
源碼分享:
import cfg from modules import breakoutClone '''主函數''' def main(): game = breakoutClone(cfg) game.run() '''run''' if __name__ == '__main__