返回顶部
首页 > 资讯 > 后端开发 > Python >用Python写几个小游戏(附源码)
  • 816
分享到

用Python写几个小游戏(附源码)

python游戏程序 2023-08-31 10:08:53 816人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

1、小恐龙 玩法:上下控制起跳躲避 import cfgimport sysimport randomimport pygamefrom modules import *'''main'''def main(highest_score):

1、小恐龙

玩法:上下控制起跳躲避

import cfgimport sysimport randomimport pygamefrom 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 osimport sysimport cfgimport pygamefrom 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  to restart the game.'            text2 = 'Press  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 osimport sysimport randomfrom 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 cfgimport sysimport pygamefrom 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、平衡木

玩法:也是小时候的经典

import osimport sysimport pygamefrom 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()

6、外星人入侵

玩法:这让我想起了魂斗罗那第几关的boss,有点类似,不过魂斗罗那个难度肯定高点。

import osimport sysimport cfgimport randomimport pygamefrom modules import *'''开始游戏'''def startGame(screen):   clock = pygame.time.Clock()   # 加载字体   font = pygame.font.SysFont('arial', 18)   if not os.path.isfile('score'):       f = open('score', 'w')       f.write('0')       f.close()   with open('score', 'r') as f:       highest_score = int(f.read().strip())   # 敌方   enemies_group = pygame.sprite.Group()   for i in range(55):       if i < 11:           enemy = enemySprite('small', i, cfg.WHITE, cfg.WHITE)       elif i < 33:           enemy = enemySprite('medium', i, cfg.WHITE, cfg.WHITE)       else:           enemy = enemySprite('large', i, cfg.WHITE, cfg.WHITE)       enemy.rect.x = 85 + (i % 11) * 50       enemy.rect.y = 120 + (i // 11) * 45       enemies_group.add(enemy)   boomed_enemies_group = pygame.sprite.Group()   en_bullets_group = pygame.sprite.Group()   ufo = ufoSprite(color=cfg.RED)   # 我方   myaircraft = aircraftSprite(color=cfg.GREEN, bullet_color=cfg.WHITE)   my_bullets_group = pygame.sprite.Group()   # 用于控制敌方位置更新   # --移动一行   enemy_move_count = 24   enemy_move_interval = 24   enemy_move_flag = False   # --改变移动方向(改变方向的同时集体下降一次)   enemy_change_direction_count = 0   enemy_change_direction_interval = 60   enemy_need_down = False   enemy_move_right = True   enemy_need_move_row = 6   enemy_max_row = 5   # 用于控制敌方发射子弹   enemy_shot_interval = 100   enemy_shot_count = 0   enemy_shot_flag = False   # 游戏进行中   running = True   is_win = False   # 主循环   while running:       screen.fill(cfg.BLACK)       for event in pygame.event.get():           # --点右上角的X或者按Esc键退出游戏           if event.type == pygame.QUIT:               pygame.quit()               sys.exit()           if event.type == pygame.KEYDOWN:               if event.key == pygame.K_ESCAPE:                   pygame.quit()                   sys.exit()           # --射击           if event.type == pygame.MOUSEBUTTONDOWN:               my_bullet = myaircraft.shot()               if my_bullet:                   my_bullets_group.add(my_bullet)       # --我方子弹与敌方/UFO碰撞检测       for enemy in enemies_group:           if pygame.sprite.spritecollide(enemy, my_bullets_group, True, None):               boomed_enemies_group.add(enemy)               enemies_group.remove(enemy)               myaircraft.score += enemy.reward       if pygame.sprite.spritecollide(ufo, my_bullets_group, True, None):           ufo.is_dead = True           myaircraft.score += ufo.reward       # --更新并画敌方       # ----敌方子弹       enemy_shot_count += 1       if enemy_shot_count > enemy_shot_interval:           enemy_shot_flag = True           enemies_survive_list = [enemy.number for enemy in enemies_group]           shot_number = random.choice(enemies_survive_list)           enemy_shot_count = 0       # ----敌方移动       enemy_move_count += 1       if enemy_move_count > enemy_move_interval:           enemy_move_count = 0           enemy_move_flag = True           enemy_need_move_row -= 1           if enemy_need_move_row == 0:               enemy_need_move_row = enemy_max_row           enemy_change_direction_count += 1           if enemy_change_direction_count > enemy_change_direction_interval:               enemy_change_direction_count = 1               enemy_move_right = not enemy_move_right               enemy_need_down = True               # ----每次下降提高移动和射击速度               enemy_move_interval = max(15, enemy_move_interval-3)               enemy_shot_interval = max(50, enemy_move_interval-10)       # ----遍历更新       for enemy in enemies_group:           if enemy_shot_flag:               if enemy.number == shot_number:                   en_bullet = enemy.shot()                   en_bullets_group.add(en_bullet)           if enemy_move_flag:               if enemy.number in range((enemy_need_move_row-1)*11, enemy_need_move_row*11):                   if enemy_move_right:                       enemy.update('right', cfg.SCREENSIZE[1])                   else:                       enemy.update('left', cfg.SCREENSIZE[1])           else:               enemy.update(None, cfg.SCREENSIZE[1])           if enemy_need_down:               if enemy.update('down', cfg.SCREENSIZE[1]):                   running = False                   is_win = False               enemy.change_count -= 1           enemy.draw(screen)       enemy_move_flag = False       enemy_need_down = False       enemy_shot_flag = False       # ----敌方爆炸特效       for boomed_enemy in boomed_enemies_group:           if boomed_enemy.boom(screen):               boomed_enemies_group.remove(boomed_enemy)               del boomed_enemy       # --敌方子弹与我方飞船碰撞检测       if not myaircraft.one_dead:           if pygame.sprite.spritecollide(myaircraft, en_bullets_group, True, None):               myaircraft.one_dead = True       if myaircraft.one_dead:           if myaircraft.boom(screen):               myaircraft.resetBoom()               myaircraft.num_life -= 1               if myaircraft.num_life < 1:                   running = False                   is_win = False       else:           # ----更新飞船           myaircraft.update(cfg.SCREENSIZE[0])           # ----画飞船           myaircraft.draw(screen)       if (not ufo.has_boomed) and (ufo.is_dead):           if ufo.boom(screen):               ufo.has_boomed = True       else:           # ----更新UFO           ufo.update(cfg.SCREENSIZE[0])           # ----画UFO           ufo.draw(screen)       # --画我方飞船子弹       for bullet in my_bullets_group:           if bullet.update():               my_bullets_group.remove(bullet)               del bullet           else:               bullet.draw(screen)       # --画敌方子弹       for bullet in en_bullets_group:           if bullet.update(cfg.SCREENSIZE[1]):               en_bullets_group.remove(bullet)               del bullet           else:               bullet.draw(screen)       if myaircraft.score > highest_score:           highest_score = myaircraft.score       # --得分每增加2000我方飞船增加一条生命       if (myaircraft.score % 2000 == 0) and (myaircraft.score > 0) and (myaircraft.score != myaircraft.old_score):           myaircraft.old_score = myaircraft.score           myaircraft.num_life = min(myaircraft.num_life + 1, myaircraft.max_num_life)       # --敌人都死光了的话就胜利了       if len(enemies_group) < 1:           is_win = True           running = False       # --显示文字       # ----当前得分       showText(screen, 'SCORE: ', cfg.WHITE, font, 200, 8)       showText(screen, str(myaircraft.score), cfg.WHITE, font, 200, 24)       # ----敌人数量       showText(screen, 'ENEMY: ', cfg.WHITE, font, 370, 8)       showText(screen, str(len(enemies_group)), cfg.WHITE, font, 370, 24)       # ----历史最高分       showText(screen, 'HIGHEST: ', cfg.WHITE, font, 540, 8)       showText(screen, str(highest_score), cfg.WHITE, font, 540, 24)       # ----FPS       showText(screen, 'FPS: ' + str(int(clock.get_fps())), cfg.RED, font, 8, 8)       # --显示剩余生命值       showLife(screen, myaircraft.num_life, cfg.GREEN)       pygame.display.update()       clock.tick(cfg.FPS)   with open('score', 'w') as f:       f.write(str(highest_score))   return is_win'''主函数'''def main():   # 初始化   pygame.init()   pygame.display.set_caption('外星人入侵 —— 九歌')   screen = pygame.display.set_mode(cfg.SCREENSIZE)   pygame.mixer.init()   pygame.mixer.music.load(cfg.BGMPATH)   pygame.mixer.music.set_volume(0.4)   pygame.mixer.music.play(-1)   while True:       is_win = startGame(screen)       endInterface(screen, cfg.BLACK, is_win)'''run'''if __name__ == '__main__':   main()

7、井字棋888

玩法:我打赌大家在课堂上肯定玩过这个,想想当年和同桌玩这个废了好几本本子。

from tkinter import *import tkinter.messagebox as msg root = Tk()root.title('TIC-TAC-TOE---Project Gurukul')# labelsLabel(root, text="player1 : X", font="times 15").grid(row=0, column=1)Label(root, text="player2 : O", font="times 15").grid(row=0, column=2) digits = [1, 2, 3, 4, 5, 6, 7, 8, 9] # for player1 sign = X and for player2 sign= Ymark = '' # counting the no. of clickcount = 0 panels = ["panel"] * 10  def win(panels, sign):    return ((panels[1] == panels[2] == panels[3] == sign)            or (panels[1] == panels[4] == panels[7] == sign)            or (panels[1] == panels[5] == panels[9] == sign)            or (panels[2] == panels[5] == panels[8] == sign)            or (panels[3] == panels[6] == panels[9] == sign)            or (panels[3] == panels[5] == panels[7] == sign)            or (panels[4] == panels[5] == panels[6] == sign)            or (panels[7] == panels[8] == panels[9] == sign))  def checker(digit):    global count, mark, digits     # Check which button clicked     if digit == 1 and digit in digits:        digits.remove(digit)        ##player1 will play if the value of count is even and for odd player2 will play        if count % 2 == 0:            mark = 'X'            panels[digit] = mark        elif count % 2 != 0:            mark = 'O'            panels[digit] = mark         button1.config(text=mark)        count = count + 1        sign = mark         if (win(panels, sign) and sign == 'X'):            msg.showinfo("Result", "Player1 wins")            root.destroy()        elif (win(panels, sign) and sign == 'O'):            msg.showinfo("Result", "Player2 wins")            root.destroy()     if digit == 2 and digit in digits:        digits.remove(digit)         if count % 2 == 0:            mark = 'X'            panels[digit] = mark        elif count % 2 != 0:            mark = 'O'            panels[digit] = mark         button2.config(text=mark)        count = count + 1        sign = mark         if (win(panels, sign) and sign == 'X'):            msg.showinfo("Result", "Player1 wins")            root.destroy()        elif (win(panels, sign) and sign == 'O'):            msg.showinfo("Result", "Player2 wins")            root.destroy()     if digit == 3 and digit in digits:        digits.remove(digit)         if count % 2 == 0:            mark = 'X'            panels[digit] = mark        elif count % 2 != 0:            mark = 'O'            panels[digit] = mark         button3.config(text=mark)        count = count + 1        sign = mark         if (win(panels, sign) and sign == 'X'):            msg.showinfo("Result", "Player1 wins")            root.destroy()        elif (win(panels, sign) and sign == 'O'):            msg.showinfo("Result", "Player2 wins")            root.destroy()     if digit == 4 and digit in digits:        digits.remove(digit)         if count % 2 == 0:            mark = 'X'            panels[digit] = mark        elif count % 2 != 0:            mark = 'O'            panels[digit] = mark         button4.config(text=mark)        count = count + 1        sign = mark         if (win(panels, sign) and sign == 'X'):            msg.showinfo("Result", "Player1 wins")            root.destroy()        elif (win(panels, sign) and sign == 'O'):            msg.showinfo("Result", "Player2 wins")            root.destroy()     if digit == 5 and digit in digits:        digits.remove(digit)         if count % 2 == 0:            mark = 'X'            panels[digit] = mark        elif count % 2 != 0:            mark = 'O'            panels[digit] = mark         button5.config(text=mark)        count = count + 1        sign = mark         if (win(panels, sign) and sign == 'X'):            msg.showinfo("Result", "Player1 wins")            root.destroy()        elif (win(panels, sign) and sign == 'O'):            msg.showinfo("Result", "Player2 wins")            root.destroy()     if digit == 6 and digit in digits:        digits.remove(digit)         if count % 2 == 0:            mark = 'X'            panels[digit] = mark        elif count % 2 != 0:            mark = 'O'            panels[digit] = mark         button6.config(text=mark)        count = count + 1        sign = mark         if (win(panels, sign) and sign == 'X'):            msg.showinfo("Result", "Player1 wins")            root.destroy()        elif (win(panels, sign) and sign == 'O'):            msg.showinfo("Result", "Player2 wins")            root.destroy()     if digit == 7 and digit in digits:        digits.remove(digit)         if count % 2 == 0:            mark = 'X'            panels[digit] = mark        elif count % 2 != 0:            mark = 'O'            panels[digit] = mark         button7.config(text=mark)        count = count + 1        sign = mark         if (win(panels, sign) and sign == 'X'):            msg.showinfo("Result", "Player1 wins")            root.destroy()        elif (win(panels, sign) and sign == 'O'):            msg.showinfo("Result", "Player2 wins")            root.destroy()     if digit == 8 and digit in digits:        digits.remove(digit)         if count % 2 == 0:            mark = 'X'            panels[digit] = mark        elif count % 2 != 0:            mark = 'O'            panels[digit] = mark         button8.config(text=mark)        count = count + 1        sign = mark         if (win(panels, sign) and sign == 'X'):            msg.showinfo("Result", "Player1 wins")            root.destroy()        elif (win(panels, sign) and sign == 'O'):            msg.showinfo("Result", "Player2 wins")            root.destroy()     if digit == 9 and digit in digits:        digits.remove(digit)         if count % 2 == 0:            mark = 'X'            panels[digit] = mark        elif count % 2 != 0:            mark = 'O'            panels[digit] = mark         button9.config(text=mark)        count = count + 1        sign = mark         if (win(panels, sign) and sign == 'X'):            msg.showinfo("Result", "Player1 wins")            root.destroy()        elif (win(panels, sign) and sign == 'O'):            msg.showinfo("Result", "Player2 wins")            root.destroy()     ###if count is greater then 8 then the match has been tied    if (count > 8 and win(panels, 'X') == False and win(panels, 'O') == False):        msg.showinfo("Result", "Match Tied")        root.destroy()  ####define buttonsbutton1 = Button(root, width=15, font=('Times 16 bold'), height=7, command=lambda: checker(1))button1.grid(row=1, column=1)button2 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(2))button2.grid(row=1, column=2)button3 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(3))button3.grid(row=1, column=3)button4 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(4))button4.grid(row=2, column=1)button5 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(5))button5.grid(row=2, column=2)button6 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(6))button6.grid(row=2, column=3)button7 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(7))button7.grid(row=3, column=1)button8 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(8))button8.grid(row=3, column=2)button9 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(9))button9.grid(row=3, column=3) root.mainloop()

最后,七个小游戏到这里就没有了,不管是放松还是拿来练手,都是很不错滴。看着这密密麻麻的代码,我都要给自己一个大大的赞,你确定不赞我一个?

来源地址:https://blog.csdn.net/hxb002131/article/details/123959126

--结束END--

本文标题: 用Python写几个小游戏(附源码)

本文链接: https://lsjlt.com/news/385207.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
  • 用Python写几个小游戏(附源码)
    1、小恐龙 玩法:上下控制起跳躲避 import cfgimport sysimport randomimport pygamefrom modules import *'''main'''def main(highest_score): ...
    99+
    2023-08-31
    python 游戏程序
  • 一口气用Python写了13个小游戏(附源码)
    今天给大家分享13个游戏源码,可以自己复现玩玩,研究下里面的编程逻辑,对学习编程(特别是初学者)应该会有很大帮助。 1、吃金币 源码分享: import osimport cfgimport sysimport pygameimpo...
    99+
    2023-09-22
    python pygame 开发语言
  • Python写小游戏吃金币+打乒乓+滑雪(附源码)
    目录1、吃金币2、打乒乓3、滑雪1、吃金币 源码分享: import os import cfg import sys import pygame import random fr...
    99+
    2024-04-02
  • Python:游戏:扫雷(附源码)
    这次我们基于 pygame 来做一个扫雷,上次有园友问我代码的 python 版本,我说明一下,我所有的代码都是基于 python 3.6 的。 先看截图,仿照 XP 上的扫雷做的,感觉 XP 上的样式比 win7 上的好看多了。 原谅...
    99+
    2023-01-30
    源码 游戏 Python
  • 14 个Python小游戏 源码分享
    目录1、吃金币2、打乒乓3、滑雪4、并夕夕版飞机大战5、打地鼠6、小恐龙7、消消乐8、俄罗斯方块9、贪吃蛇10、24点小游戏11、平衡木12、外星人入侵13、贪心鸟14、井字棋888...
    99+
    2024-04-02
  • 【pygame游戏】用Python实现一个蔡徐坤大战篮球的小游戏,可还行?【附源码】
    Python制作坤坤打篮球小游戏 序言准备工作开发环境 效果预览开始界面游戏规则结束游戏 代码实现 序言 话说在前面,我不是小黑子~ 我是超级大黑子😏 ...
    99+
    2023-09-02
    python pygame 游戏 篮球
  • 30个Python小游戏,上班摸鱼我能玩一天【内附源码】
    大家好,我是辣条。 今天给大家带来30个py小游戏,一定要收藏! 目录 有手就行 1、吃金币 2、打乒乓 3、滑雪 4、并夕夕版飞机大战 5、打地鼠 简简单单 6、小恐龙 7、消消乐 8、俄罗斯方块 9、贪吃蛇 普普通通 10、24点小游戏...
    99+
    2023-09-02
    游戏程序 pygame 程序人生 python 游戏
  • 手把手教你使用Python写贪吃蛇游戏(pygame,附源码)
    贪吃蛇游戏是有史以来最受欢迎的街机游戏之一。在这个游戏中,玩家的主要目标是在不撞墙或不撞墙的情况下抓住最大数量的水果。在学习 Python 或 Pygame 时,可以将创建蛇游戏视为一项挑战。这是每个新手程序员都应该接受的最好的初学者友好项...
    99+
    2023-08-31
    pygame python 算法 开发语言
  • Python编写简易猜数字小游戏(附完整代码)
    Python编写简易猜数字小游戏(附完整代码) 猜数字游戏是一款非常经典的小游戏,本文将介绍如何使用Python编写一个简易的猜数字游戏,并提供完整的源代码。 首先,让我们了解一下游戏规则。游戏开始时...
    99+
    2023-09-23
    python java 开发语言
  • 微信小程序游戏开发│石头剪刀布游戏(附源码)
     石头剪刀布游戏功能中一方是电脑,另一方是玩家。游戏时电脑一直快速切换出拳显示,当玩家选择底部的剪子、石头、布后,则电脑出拳停止,并在紫色方块中显示用户的出拳图片。游戏判断出输赢结果,记录玩家赢的次数。对战一局后可以单击“再来!”按钮...
    99+
    2023-09-02
    游戏 小程序 微信小程序
  • 用python做简单的小游戏,如何用python写小游戏
    大家好,小编来为大家解答以下问题,初学者怎么用python写简单小游戏教程,如何用python编写一个简单的小游戏,今天让我们一起来看看吧! 1、python简单小游戏代码   1、Python猜拳小游戏代码:   2、import r...
    99+
    2023-09-08
    人工智能
  • Java实现贪吃蛇大作战小游戏(附源码)
    目录1.开发环境及游戏展示1.1 游戏主界面1.2 移动界面1.3 奖励界面1.4 F加速功能界面1.5 死亡界面2.需求分析3.系统设计3.1 系统总体功能设计3.2 系统总体流程...
    99+
    2024-04-02
  • 炸弹人小游戏代码开源(python)
    ♥️作者:小刘在C站 ♥️个人主页:小刘主页 ♥️每天分享云计算网络运维课堂笔记,努力不一定有回报,但一定会有收获加油!一起努力,共赴美好人生! ♥️夕阳下,是最美的绽放,当遵从一心,踏浪而往,纵千山万水, 也要抵达。 目录 一...
    99+
    2023-09-02
    python pygame 开发语言
  • 用Python写一个无界面的2048小游戏
    以前游戏2048火的时候,正好用其他的语言编写了一个,现在学习python,正好想起来,便决定用python写一个2048,由于没学过python里面的界面编程,所以写了一个极其简单的无界面2048。游戏2...
    99+
    2022-06-04
    小游戏 界面 Python
  • 使用python+pygame开发消消乐游戏附完整源码
    目录一、环境要求二、游戏简介三、完整开发流程1、项目主结构2、详细配置3、消消乐所有图形加载4、随机生成初始布局、相邻消除、自动下落5、随机初始化消消乐的主图内容四、如何启动游戏呢?...
    99+
    2024-04-02
  • c/c++小游戏源代码
    翻到开学之初写的一些小游戏,陆续给大家发出来,也便提高新手们的编程兴趣。(已详细注释) 几个对应头文件需要注意一下,但不必太过恐慌,因为,,,很多,用的时候找需要的即可 (在Dev,...
    99+
    2024-04-02
  • 2048小游戏成品源码
    2048小游戏,可以自选背景颜色,方框颜色,音乐播放。 还可以展示当前玩家的排名,动态排名,及历史玩家的排名。 前期需求: 使用pygame加载目录音乐。MP3文件: def music_play...
    99+
    2023-08-30
    pygame python 开发语言
  • Python实现小游戏的源代码示例
    这篇文章将为大家详细讲解有关Python实现小游戏的源代码示例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。1、21点数字小游戏展示:首先配置文件的源码:'''配置文件'&...
    99+
    2023-06-14
  • Python基于pygame实现的font游戏字体(附源码)
    本文实例讲述了Python基于pygame实现的font游戏字体。分享给大家供大家参考,具体如下: 在pygame游戏开发中,一个友好的UI中,漂亮的字体是少不了的 今天就给大伙带来有关pygame中字体的...
    99+
    2022-06-04
    源码 字体 游戏
  • 教你用Python写一个水果忍者小游戏
    目录引言一、需要导入的包二、窗口界面设置  三、随机生成水果位置    四、绘制字体  五、玩家生命的提示六、游戏开始与结束的画面  ...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作