有趣的MATLAB 1.游戏程序

合集下载

13个有趣又好玩的Python游戏代码分享

13个有趣又好玩的Python游戏代码分享

13个有趣⼜好玩的Python游戏代码分享⽬录1、吃⾦币2、打乒乓3、滑雪4、并⼣⼣版飞机⼤战5、打地⿏6、⼩恐龙7、消消乐8、俄罗斯⽅块9、贪吃蛇10、24点⼩游戏11、平衡⽊12、外星⼈⼊侵13、井字棋888经常听到有朋友说,学习编程是⼀件⾮常枯燥⽆味的事情。

其实,⼤家有没有认真想过,可能是我们的学习⽅法不对?⽐⽅说,你有没有想过,可以通过打游戏来学编程?今天我想跟⼤家分享⼏个Python⼩游戏,教你如何通过边打游戏边学编程!1、吃⾦币源码分享:import osimport cfgimport sysimport pygameimport randomfrom modules import *'''游戏初始化'''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 = pygame.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():pass2、打乒乓源码分享:import sysimport cfgimport pygamefrom modules import *'''定义按钮'''def Button(screen, position, text, button_size=(200, 50)):left, top = positionbwidth, bheight = button_sizepygame.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))'''Function:开始界⾯Input:--screen: 游戏界⾯Return:--game_mode: 1(单⼈模式)/2(双⼈模式)'''def startInterface(screen):clock = pygame.time.Clock()while True: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 1elif button_2.collidepoint(pygame.mouse.get_pos()):return 2clock.tick(10)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]]while True: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:returnelif event.key == pygame.K_ESCAPE:sys.exit()pygame.quit()for text, pos in zip(texts, positions):screen.blit(text, pos)clock.tick(10)pygame.display.update()'''运⾏游戏Demo'''def runDemo(screen):# 加载游戏素材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控制, 仅双⼈模式时可控制)score_left = 0racket_left = Racket(cfg.RACKETPICPATH, 'LEFT', cfg)# --右边球拍(↑↓控制)score_right = 0racket_right = Racket(cfg.RACKETPICPATH, 'RIGHT', cfg)# --球ball = Ball(cfg.BALLPICPATH, cfg)clock = pygame.time.Clock()while True: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')else: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_rightclock.tick(100)pygame.display.update()'''主函数'''def main():# 初始化pygame.init()pygame.mixer.init()screen = pygame.display.set_mode((cfg.WIDTH, cfg.HEIGHT))pygame.display.set_caption('pingpong —— 九歌')# 开始游戏while True:score_left, score_right = runDemo(screen)endInterface(screen, score_left, score_right)'''run'''if __name__ == '__main__':main()3、滑雪源码分享:import sysimport cfgimport pygameimport random'''滑雪者类'''class SkierClass(pygame.sprite.Sprite):def __init__(self):pygame.sprite.Sprite.__init__(self)# 滑雪者的朝向(-2到2)self.direction = 0self.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为向前'''def turn(self, num):self.direction += numself.direction = max(-2, self.direction)self.direction = min(2, self.direction)center = self.rect.centerself.image = pygame.image.load(self.imagepaths[self.direction])self.rect = self.image.get_rect()self.rect.center = centerself.speed = [self.direction, 6-abs(self.direction)*2]return self.speed'''移动滑雪者'''def move(self):self.rect.centerx += self.speed[0]self.rect.centerx = max(20, self.rect.centerx)self.rect.centerx = min(620, self.rect.centerx)'''设置为摔倒状态'''def setFall(self):self.image = pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])'''设置为站⽴状态'''def setForward(self):self.direction = 0self.image = pygame.image.load(self.imagepaths[self.direction]) '''Function:障碍物类Input:img_path: 障碍物图⽚路径location: 障碍物位置attribute: 障碍物类别属性'''class ObstacleClass(pygame.sprite.Sprite):def __init__(self, img_path, location, attribute):pygame.sprite.Sprite.__init__(self)self.img_path = img_pathself.image = pygame.image.load(self.img_path)self.location = locationself.rect = self.image.get_rect()self.rect.center = self.locationself.attribute = attributeself.passed = False'''移动'''def move(self, num):self.rect.centery = self.location[1] - num'''创建障碍物'''def createObstacles(s, e, num=10):obstacles = pygame.sprite.Group()locations = []for i in range(num):row = random.randint(s, e)col = random.randint(0, 9)location = [col*64+20, row*64+20]if location not in locations:locations.append(location)attribute = random.choice(list(cfg.OBSTACLE_PATHS.keys())) img_path = cfg.OBSTACLE_PATHS[attribute]obstacle = ObstacleClass(img_path, location, attribute)obstacles.add(obstacle)return obstacles'''合并障碍物'''def AddObstacles(obstacles0, obstacles1):obstacles = pygame.sprite.Group()for obstacle in obstacles0:obstacles.add(obstacle)for obstacle in obstacles1:obstacles.add(obstacle)return obstacles'''显⽰游戏开始界⾯'''def ShowStartInterface(screen, screensize):screen.fill((255, 255, 255))tfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//5)cfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//20)title = tfont.render(u'滑雪游戏', True, (255, 0, 0))content = cfont.render(u'按任意键开始游戏', True, (0, 0, 255))trect = title.get_rect()trect.midtop = (screensize[0]/2, screensize[1]/5)crect = content.get_rect()crect.midtop = (screensize[0]/2, screensize[1]/2)screen.blit(title, trect)screen.blit(content, crect)while True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()elif event.type == pygame.KEYDOWN:returnpygame.display.update()'''显⽰分数'''def showScore(screen, score, pos=(10, 10)):font = pygame.font.Font(cfg.FONTPATH, 30)score_text = font.render("Score: %s" % score, True, (0, 0, 0))screen.blit(score_text, pos)'''更新当前帧的游戏画⾯'''def updateFrame(screen, obstacles, skier, score):screen.fill((255, 255, 255))obstacles.draw(screen)screen.blit(skier.image, skier.rect)showScore(screen, score)pygame.display.update()'''主程序'''def main():# 游戏初始化pygame.init()pygame.mixer.init()pygame.mixer.music.load(cfg.BGMPATH)pygame.mixer.music.set_volume(0.4)pygame.mixer.music.play(-1)# 设置屏幕screen = pygame.display.set_mode(cfg.SCREENSIZE)pygame.display.set_caption('滑雪游戏 —— 九歌')# 游戏开始界⾯ShowStartInterface(screen, cfg.SCREENSIZE)# 实例化游戏精灵# --滑雪者skier = SkierClass()# --创建障碍物obstacles0 = createObstacles(20, 29)obstacles1 = createObstacles(10, 19)obstaclesflag = 0obstacles = AddObstacles(obstacles0, obstacles1)# 游戏clockclock = pygame.time.Clock()# 记录滑雪的距离distance = 0# 记录当前的分数score = 0# 记录当前的速度speed = [0, 6]# 游戏主循环while True:# --事件捕获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_LEFT or event.key == pygame.K_a:speed = skier.turn(-1)elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:speed = skier.turn(1)# --更新当前游戏帧的数据skier.move()distance += speed[1]if distance >= 640 and obstaclesflag == 0:obstaclesflag = 1obstacles0 = createObstacles(20, 29)obstacles = AddObstacles(obstacles0, obstacles1)if distance >= 1280 and obstaclesflag == 1:obstaclesflag = 0distance -= 1280for obstacle in obstacles0:obstacle.location[1] = obstacle.location[1] - 1280obstacles1 = createObstacles(10, 19)obstacles = AddObstacles(obstacles0, obstacles1)for obstacle in obstacles:obstacle.move(distance)# --碰撞检测hitted_obstacles = pygame.sprite.spritecollide(skier, obstacles, False)if hitted_obstacles:if hitted_obstacles[0].attribute == "tree" and not hitted_obstacles[0].passed: score -= 50skier.setFall()updateFrame(screen, obstacles, skier, score)pygame.time.delay(1000)skier.setForward()speed = [0, 6]hitted_obstacles[0].passed = Trueelif hitted_obstacles[0].attribute == "flag" and not hitted_obstacles[0].passed: score += 10obstacles.remove(hitted_obstacles[0])# --更新屏幕updateFrame(screen, obstacles, skier, score)clock.tick(cfg.FPS)'''run'''if __name__ == '__main__':main();4、并⼣⼣版飞机⼤战源码分享:import sysimport cfgimport pygamefrom modules import *'''游戏界⾯'''def GamingInterface(num_player, screen):# 初始化pygame.mixer.music.load(cfg.SOUNDPATHS['Cool Space Music'])pygame.mixer.music.set_volume(0.4)pygame.mixer.music.play(-1)explosion_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['boom'])fire_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['shot'])font = pygame.font.Font(cfg.FONTPATH, 20)# 游戏背景图bg_imgs = [cfg.IMAGEPATHS['bg_big'], cfg.IMAGEPATHS['seamless_space'], cfg.IMAGEPATHS['space3']] bg_move_dis = 0bg_1 = pygame.image.load(bg_imgs[0]).convert()bg_2 = pygame.image.load(bg_imgs[1]).convert()bg_3 = pygame.image.load(bg_imgs[2]).convert()# 玩家, ⼦弹和⼩⾏星精灵组player_group = pygame.sprite.Group()bullet_group = pygame.sprite.Group()asteroid_group = pygame.sprite.Group()# 产⽣⼩⾏星的时间间隔asteroid_ticks = 90for i in range(num_player):player_group.add(Ship(i+1, cfg))clock = pygame.time.Clock()# 分数score_1, score_2 = 0, 0# 游戏主循环while True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()# --玩家⼀: ↑↓←→控制, j射击; 玩家⼆: wsad控制, 空格射击pressed_keys = pygame.key.get_pressed()for idx, player in enumerate(player_group):direction = Noneif idx == 0:if pressed_keys[pygame.K_UP]:direction = 'up'elif pressed_keys[pygame.K_DOWN]:direction = 'down'elif pressed_keys[pygame.K_LEFT]:direction = 'left'elif pressed_keys[pygame.K_RIGHT]:direction = 'right'if direction:player.move(direction)if pressed_keys[pygame.K_j]:if player.cooling_time == 0:fire_sound.play()bullet_group.add(player.shot())player.cooling_time = 20elif idx == 1:if pressed_keys[pygame.K_w]:direction = 'up'elif pressed_keys[pygame.K_s]:direction = 'down'elif pressed_keys[pygame.K_a]:direction = 'left'elif pressed_keys[pygame.K_d]:direction = 'right'if direction:player.move(direction)if pressed_keys[pygame.K_SPACE]:if player.cooling_time == 0:fire_sound.play()bullet_group.add(player.shot())player.cooling_time = 20if player.cooling_time > 0:player.cooling_time -= 1if (score_1 + score_2) < 500:background = bg_1elif (score_1 + score_2) < 1500:background = bg_2else:background = bg_3# --向下移动背景图实现飞船向上移动的效果screen.blit(background, (0, -background.get_rect().height + bg_move_dis))screen.blit(background, (0, bg_move_dis))bg_move_dis = (bg_move_dis + 2) % background.get_rect().height# --⽣成⼩⾏星if asteroid_ticks == 0:asteroid_ticks = 90asteroid_group.add(Asteroid(cfg))else:asteroid_ticks -= 1# --画飞船for player in player_group:if pygame.sprite.spritecollide(player, asteroid_group, True, None): player.explode_step = 1explosion_sound.play()elif player.explode_step > 0:if player.explode_step > 3:player_group.remove(player)if len(player_group) == 0:returnelse:player.explode(screen)else:player.draw(screen)# --画⼦弹for bullet in bullet_group:bullet.move()if pygame.sprite.spritecollide(bullet, asteroid_group, True, None): bullet_group.remove(bullet)if bullet.player_idx == 1:score_1 += 1else:score_2 += 1else:bullet.draw(screen)# --画⼩⾏星for asteroid in asteroid_group:asteroid.move()asteroid.rotate()asteroid.draw(screen)# --显⽰分数score_1_text = '玩家⼀得分: %s' % score_1score_2_text = '玩家⼆得分: %s' % score_2text_1 = font.render(score_1_text, True, (0, 0, 255))text_2 = font.render(score_2_text, True, (255, 0, 0))screen.blit(text_1, (2, 5))screen.blit(text_2, (2, 35))# --屏幕刷新pygame.display.update()clock.tick(60)'''主函数'''def main():pygame.init()pygame.font.init()pygame.mixer.init()screen = pygame.display.set_mode(cfg.SCREENSIZE)pygame.display.set_caption('飞机⼤战 —— 九歌')num_player = StartInterface(screen, cfg)if num_player == 1:while True:GamingInterface(num_player=1, screen=screen)EndInterface(screen, cfg)else:while True:GamingInterface(num_player=2, screen=screen)EndInterface(screen, cfg)'''run'''if __name__ == '__main__':main()5、打地⿏源码分享:import cfgimport sysimport pygameimport randomfrom modules import *'''游戏初始化'''def initGame():pygame.init()pygame.mixer.init()screen = pygame.display.set_mode(cfg.SCREENSIZE)pygame.display.set_caption('打地⿏ —— 九歌')'''主函数'''def main():# 初始化screen = initGame()# 加载背景⾳乐和其他⾳效pygame.mixer.music.load(cfg.BGM_PATH)pygame.mixer.music.play(-1)audios = {'count_down': pygame.mixer.Sound(cfg.COUNT_DOWN_SOUND_PATH), 'hammering': pygame.mixer.Sound(cfg.HAMMERING_SOUND_PATH)}# 加载字体font = pygame.font.Font(cfg.FONT_PATH, 40)# 加载背景图⽚bg_img = pygame.image.load(cfg.GAME_BG_IMAGEPATH)# 开始界⾯startInterface(screen, cfg.GAME_BEGIN_IMAGEPATHS)# 地⿏改变位置的计时hole_pos = random.choice(cfg.HOLE_POSITIONS)change_hole_event = EREVENTpygame.time.set_timer(change_hole_event, 800)# 地⿏mole = Mole(cfg.MOLE_IMAGEPATHS, hole_pos)# 锤⼦hammer = Hammer(cfg.HAMMER_IMAGEPATHS, (500, 250))# 时钟clock = pygame.time.Clock()# 分数your_score = 0flag = False# 初始时间init_time = pygame.time.get_ticks()# 游戏主循环while True:# --游戏时间为60stime_remain = round((61000 - (pygame.time.get_ticks() - init_time)) / 1000.) # --游戏时间减少, 地⿏变位置速度变快if time_remain == 40 and not flag:hole_pos = random.choice(cfg.HOLE_POSITIONS)mole.reset()mole.setPosition(hole_pos)pygame.time.set_timer(change_hole_event, 650)flag = Trueelif time_remain == 20 and flag:hole_pos = random.choice(cfg.HOLE_POSITIONS)mole.reset()mole.setPosition(hole_pos)pygame.time.set_timer(change_hole_event, 500)flag = False# --倒计时⾳效if time_remain == 10:audios['count_down'].play()# --游戏结束if time_remain < 0: breakcount_down_text = font.render('Time: '+str(time_remain), True, cfg.WHITE) # --按键检测for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()elif event.type == pygame.MOUSEMOTION:hammer.setPosition(pygame.mouse.get_pos())elif event.type == pygame.MOUSEBUTTONDOWN:if event.button == 1:hammer.setHammering()elif event.type == change_hole_event:hole_pos = random.choice(cfg.HOLE_POSITIONS)mole.reset()mole.setPosition(hole_pos)# --碰撞检测if hammer.is_hammering and not mole.is_hammer:is_hammer = pygame.sprite.collide_mask(hammer, mole)if is_hammer:audios['hammering'].play()mole.setBeHammered()your_score += 10# --分数your_score_text = font.render('Score: '+str(your_score), True, cfg.BROWN) # --绑定必要的游戏元素到屏幕(注意顺序)screen.blit(bg_img, (0, 0))screen.blit(count_down_text, (875, 8))screen.blit(your_score_text, (800, 430))mole.draw(screen)hammer.draw(screen)# --更新pygame.display.flip()# 读取最佳分数(try块避免第⼀次游戏⽆.rec⽂件)try:best_score = int(open(cfg.RECORD_PATH).read())except:best_score = 0# 若当前分数⼤于最佳分数则更新最佳分数if your_score > best_score:f = open(cfg.RECORD_PATH, 'w')f.write(str(your_score))f.close()# 结束界⾯score_info = {'your_score': your_score, 'best_score': best_score}is_restart = endInterface(screen, cfg.GAME_END_IMAGEPATH, cfg.GAME_AGAIN_IMAGEPATHS, score_info, cfg.FONT_PATH, [cfg.WHITE, cfg.RED], cfg.SCREENSIZE) return is_restart'''run'''if __name__ == '__main__':while True:is_restart = main()if not is_restart:break6、⼩恐龙玩法:上下控制起跳躲避源码分享: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 = 0score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(534, 15), bg_color=cfg.BACKGROUND_COLOR)highest_score = highest_scorehighest_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 = 0score_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 += 1if add_obstacle_timer > random.randrange(50, 150):add_obstacle_timer = 0random_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 += 1if score_timer > (cfg.FPS//12):score_timer = 0score += 1score = min(score, 99999)if score > highest_score:highest_score = scoreif score % 100 == 0:sounds['point'].play()if score % 1000 == 0:ground.speed -= 1for item in cloud_sprites_group:item.speed -= 1for item in cactus_sprites_group:item.speed -= 1for 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 = 0while True:flag, highest_score = main(highest_score)if not flag: break7、消消乐玩法:三个相连就能消除源码分享: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 = 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()8、俄罗斯⽅块玩法:童年经典,普通模式没啥意思,⼩时候我们都是玩加速的。

MATLAB课程设计

MATLAB课程设计

MATLAB课程设计课程设计(论文)题目:用MATLAB语言程序开发凑五子棋游戏专业:信息与计算科学指导教师:张大海学生姓名:谢艳涛班级-学号:信计131-30学生姓名:黄元福班级-学号:信计131-26学生姓名:辛安班级-学号:信计131-222016年 11月摘要凑五子棋是一种两人对弈的纯策略型棋类游戏,应用MATLAB语言编写程序可以在计算机上实现二人对弈凑五子棋功能。

二人对弈凑五子棋程序由欢迎界面显示、游戏界面生成、光标移动与落子、判断胜负、悔棋功能、提供音效等子程序构成;程序中应用了结构体、数组、全局变量、按键处理和图形编程等元素和语句。

程序通过棋盘和棋子图像生成、二人移子与落子和判断胜负等功能的实现,在计算机上实现了二人凑五子棋对弈。

目录摘要-------------------------------------------------- II 第1章:需求分析 ---------------------------------------- 11.1凑五子棋背景 ----------------------------------- 11.2 凑五子棋需求分析和流程设计--------------------- 1 第2章:概要设计 ---------------------------------------- 72.1 各类头文件和全局变量--------------------------- 72.2 画面显示模块----------------------------------- 8 第3章:详细设计 --------------------------------------- 103.1 玩家操作模块---------------------------------- 103.2音效提供模块 ---------------------------------- 113.3 胜负判断模块---------------------------------- 11 第4章:调试分析 --------------------------------------- 124.1 图形模块-------------------------------------- 12 4.2 玩家操作模块 ------------------------------------ 134.3 胜负判断模块---------------------------------- 14 第5章:用户手册 --------------------------------------- 14第6章:小组分工 --------------------------------------- 15 第7章:结论与心得 ------------------------------------- 16 第8章:源程序代码 ------------------------------------ 16第1章:需求分析1.1凑五子棋背景传统凑五子棋的棋具与围棋相同,棋子分为黑白两色,棋盘为18×18,棋子放置于棋盘线交叉点上。

matlab有趣的代码

matlab有趣的代码

matlab有趣的代码Matlab是一种用于科学计算和数据可视化的强大工具。

它不仅可以解决数学问题,还可以进行图像处理、信号处理、机器学习等等。

在这篇文章中,我将为大家介绍一些有趣的Matlab代码,并解释它们的功能和应用。

1. "音乐可视化" - 利用Matlab可以将音频信号转换为可视化效果。

你可以使用Matlab的音频处理库来读取音频文件,并将其转换为时域或频域信号。

然后,你可以使用Matlab的绘图功能将这些信号可视化成波形图或频谱图。

2. "图像滤镜效果" - Matlab提供了丰富的图像处理工具箱,可以实现各种有趣的图像滤镜效果。

比如,你可以使用Matlab的边缘检测算法来突出图像的边缘特征,或者使用模糊滤镜来模糊图像。

这些滤镜效果可以使图像更加有趣和艺术化。

3. "模拟物理实验" - Matlab可以用来模拟各种物理实验,比如弹簧振子、摆钟等。

你可以使用Matlab的数值计算功能来解决物理方程,并使用Matlab的绘图功能将模拟结果可视化。

这样,你就可以通过代码实现自己的物理实验,并观察其行为和变化。

4. "游戏开发" - Matlab不仅可以用于科学计算和数据处理,还可以用于游戏开发。

你可以使用Matlab的图形库来创建简单的游戏界面,并使用Matlab的控制语句和逻辑运算来实现游戏的逻辑。

这样,你就可以通过编写Matlab代码来开发自己的小游戏。

5. "数据可视化" - Matlab提供了丰富的绘图和可视化工具,可以帮助你更好地理解和展示数据。

你可以使用Matlab的绘图函数来绘制各种统计图表,比如柱状图、折线图、散点图等。

这些图表可以帮助你更直观地理解数据的分布和趋势。

6. "机器学习应用" - Matlab提供了强大的机器学习工具箱,可以帮助你构建和训练机器学习模型。

Python小游戏代码

Python小游戏代码

Python5个小游戏代码1. 猜数字游戏import randomdef guess_number():random_number = random.randint(1, 100)attempts = 0while True:user_guess = int(input("请输入一个1到100之间的数字:"))attempts += 1if user_guess > random_number:print("太大了,请再试一次!")elif user_guess < random_number:print("太小了,请再试一次!")else:print(f"恭喜你,猜对了!你用了{attempts}次尝试。

")breakguess_number()这个猜数字游戏的规则很简单,程序随机生成一个1到100之间的数字,然后玩家通过输入猜测的数字来与随机数进行比较。

如果猜测的数字大于或小于随机数,程序会给出相应的提示。

直到玩家猜对为止,程序会显示恭喜消息,并告诉玩家猜对所用的尝试次数。

2. 石头、剪刀、布游戏import randomdef rock_paper_scissors():choices = ['石头', '剪刀', '布']while True:user_choice = input("请选择(石头、剪刀、布):")if user_choice not in choices:print("无效的选择,请重新输入!")continuecomputer_choice = random.choice(choices)print(f"你选择了:{user_choice}")print(f"电脑选择了:{computer_choice}")if user_choice == computer_choice:print("平局!")elif (user_choice == '石头' and computer_choice == '剪刀') or \(user_choice == '剪刀' and computer_choice == '布') or \(user_choice == '布' and computer_choice == '石头'):print("恭喜你,你赢了!")else:print("很遗憾,你输了!")play_again = input("再玩一局?(是/否)")if play_again.lower() != "是" and play_again.lower() != "yes":print("游戏结束。

2048游戏matlab代码

2048游戏matlab代码

说明:本代码为2048嬉戏matlab代码,程序未进行嬉戏结束判定,节目如下。

function g2048(action)global totalscore flag score_boardif nargin<1figure_h=figure;set(figure_h,'Units','points')set(figure_h,'UserData',figure_h);totalscore=0;flag=0;score_board=zeros(1,16);action='initialize';endswitch actioncase'initialize';figure_h=get(gcf,'UserData');set(figure_h,...'Color',[0.4 0.4 0.4],...'Menubar','none',...'Name','2048',...'NumberTitle','off',...'Position',[200 200 320 355],...'Resize','off');axis('off')game_score=uicontrol(figure_h,...'BackgroundColor',[1 1 1],...'ForegroundColor',[0 0 0], ...'HorizontalAlignment','center',...'FontSize',12,...'Units','points',...'Position',[235 305 65 30],...'String','Score',...'Style','edit',...'Tag','game_score');new_game_h=uicontrol(figure_h,...'Callback','g2048 restart',...'FontSize',12, ...'Units','points',...'Position',[35 30 65 30],...'String','New Game',...'Style','pushbutton');% closeclose_h=uicontrol(figure_h,...'Callback','close(gcf)',...'Fontsize',12, ...'Units','points',...'Position',[225 30 65 30],...'String','Close',...'Style','pushbutton');% rightmove_right=uicontrol(figure_h,...'Callback','g2048 right',...'Fontsize',12, ...'Units','points',...'Position',[255 185 60 30],...'String','Right',...'Style','pushbutton');% leftmove_left=uicontrol(figure_h,...'Callback','g2048 left',...'Fontsize',12, ...'Units','points',...'Position',[5 185 60 30],...'String','Left',...'Style','pushbutton');% upmove_up=uicontrol(figure_h,...'Callback','g2048 up',...'Fontsize',12, ...'Units','points',...'Position',[130 300 60 30],...'String','Up',...'Style','pushbutton');% downmove_down=uicontrol(figure_h,...'Callback','g2048 down',...'Fontsize',12, ...'Units','points',...'Position',[130 80 60 30],...'String','Down',...'Style','pushbutton');% setup the game boardirows=1;for counter=1:16jcols=rem(counter,4);if jcols==0j cols=4;endposition=[40*jcols+40 85+40*irows 40 40]; index=(irows-1)*4+jcols;if jcols==4i rows=irows+1;endboard.squares(index)=uicontrol(figure_h,...'FontSize',18,...'FontWeight','bold',...'Units','points',...'Position',position,...'Style','pushbutton',...'Tag',num2str(index));endset(figure_h,'userdata',board);g2048('restart')case'restart'totalscore=0;score_board=zeros(1,16);g2048('addnum') ;g2048('addnum') ;g2048('show')case'show'num_0=find(score_board==0);board=get(gcf,'UserData');set(board.squares,{'string'},num2cell(score_board)')set(board.squares,...'BackgroundColor',[0.701961 0.701961 0.701961],...'Enable','on',...'Visible','on')set(board.squares(num_0),...'BackgroundColor','black',...'Enable','off',...'String',' ');score_handle=findobj(gcf,'Tag','game_score');s et(score_handle,...'String',num2str(totalscore),...'Tag','game_score');case'down'C=score_board;for i=1:4A=[score_board(i) score_board(i+4) score_board(i+8) score_board(i+12)];[B score]=move(A);score_board(i)=B(1); score_board(i+4)=B(2);score_board(i+8)=B(3); score_board(i+12)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'up'C=score_board;for i=13:16A=[score_board(i) score_board(i-4) score_board(i-8) score_board(i-12)];[B score]=move(A);score_board(i)=B(1); score_board(i-4)=B(2);score_board(i-8)=B(3); score_board(i-12)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'right'C=score_board;for i=4:4:16A=[score_board(i) score_board(i-1) score_board(i-2) score_board(i-3)];[B score]=move(A);score_board(i)=B(1); score_board(i-1)=B(2);score_board(i-2)=B(3); score_board(i-3)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'left'C=score_board;for i=1:4:13A=[score_board(i) score_board(i+1) score_board(i+2) score_board(i+3)];[B score]=move(A);score_board(i)=B(1); score_board(i+1)=B(2);score_board(i+2)=B(3); score_board(i+3)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'addnum'num_0=find(score_board==0);l=length(num_0);if l>0score_board(num_0(ceil(l*rand)))=2+2*(rand<0.1);endendendfunction Y=addnum(X)num_0=find(X==0);l=length(num_0);X(num_0(ceil(l*rand)))=2+2*(rand<0.1);Y=X;endfunction [B score]=move(A)score=0;for k=1:2for i=1:3if A(i)==0for j=i:3A(j)=A(j+1);endA(4)=0;endendendif A(1)==A(2)if A(3)==A(4)A(1)=A(1)+A(2);A(2)=A(3)+A(4);A(3)=0;A(4)=0;score=A(1)+A(2);else A(1)=A(1)+A(2);A(2)=A(3);A(3)=A(4);A(4)=0;score=A(1);endelse if A(2)==A(3)A(1)=A(1);A(2)=A(2)+A(3);A(3)=A(4);A(4)=0;score=A(2);else if A(3)==A(4)A(1)=A(1);A(2)=A(2);A(3)=A(3)+A(4);A(4)=0;score=A(3);else score=0;endendendB=A;end。

matlab课程设计报告模板俄罗斯方块

matlab课程设计报告模板俄罗斯方块

matlab课程设计报告模板俄罗斯方块
一.需求分析
在个人电脑日益普及的今天,一些有趣的桌面游戏已经成为人们在使用计算机进行工作或学习之余休闲娱乐的
首选,而俄罗斯方块游戏是人们最熟悉的小游戏之一,它以其趣味性强,易上手等诸多特点得到了大众的认
可,因此开发此游戏软件可满足人们的一些娱乐的需求。

此俄罗斯方块游戏可以为用户提供一个可在普通个人电脑上运行的,界面美观的,易于控制的俄罗斯方块游
戏。

二,系统运行环境
操作系统选择Windows XP版本,运行环境选择MyEclipse
三.系统功能需求描述
俄罗斯方块游戏是-款适合大众的游戏软件,它适合不同年龄的人玩。

本软件要实现的功能如下:
1.游戏区:玩家可以在游戏区中堆积方块,并能够在游戏过程中随时了解得分情况。

2.游戏控制:玩家可以通过游戏控制功能来选择开始新的一局游戏,暂停或退出游戏。

3.级别设置:玩家可以根据自己的需要自行设定游戏的开始级别,级别越高,游戏速度越快,难度越大。

四,总体设计
游戏中玩家可以做的操作有:
1.以90度为单位旋转方每一格块。

2.以格子为单位左右移动方块,让方块加速落下。

3.方块移到区域最下方或是着地到其他方块上无法移动时,就会固定在该处,而新的随机图形会出现在区域上方开始落下。

4.当区域中某一列横向格子全部由方块填满,则该列会自动消除并成为玩家的得分。

同时删除的列数越多,得分指数上升。

5.当固定的方块堆到区域最上方,则游戏结束。

五.系统结构图
六.程序模块设计。

matlab编程(五子棋)[整理版]

matlab编程(五子棋)[整理版]

function five() M文件的一种类型,以function开启的函数文件,另一种是把一系列命令结合在一起的一般M文件figure(1) 创建一个新的图形对象axis([0 12 0 12]); 坐标轴范围控制命令,axis([xmin xmax ymin ymax])用于设置图表各坐标轴的刻度范围hold on 图形保持功能,当前坐标轴和图形都将保持,此后绘制的图形都将添加在这个图形之上,并且自动调整坐标轴的范围axis off 取消坐标轴背景,在运行的图中不显示坐标for i = 1:11 a:b:c第一个为起始值,第二个为增量(增量为1,冒号省略),第三个为结束值line([1 11],[i i]); 画网格line([1,2],[3,4])将画出(1,3)到(2,4)的一条直线line([i i],[1 11]);endaxis equal 横纵坐标使用相同的刻度(使每一个格子成为正方形)qishou = 1; 判断棋手的颜色,开始的时候是红色,取0时是黑色boardstatus = zeros(10); 棋盘状态gt矩阵,取0为空,取1为黑,取2为红zeros(10)将画出10*10的零阵,代表棋盘上的100个位置while 1hold onposflag = 1; 用于判断下的棋是否有效,取1说明下的棋无效,要重新下while posflag[xpos,ypos] = ginput(1); 能从当前的坐标中读取n个点并返回这n个点的x,y坐标,均为n x1向量,程序运行时,在界面鼠标会以一个十字线移动,便是ginput(x)的功能 xpos = 0.5*(floor(xpos)+ceil(xpos)); x,y为圆心,floor(x)地板函数,即舍去正小数至最近整数 ypos = 0.5*(floor(ypos)+ceil(ypos)); ceil(x)天花板函数,即加入正小数至最近整数,例如x=9.5,floo(x)=9,ceil(x)=10 if xpos<=0.5||xpos>=11||ypos<=0.5||ypos>=11 点到棋盘外了,回到上面的循环continueendfor n=1:10 判断棋子是否下到边界,若在边线上,判断无效,继续if xpos==n||ypos==ncontinueendrx = floor(xpos); boardstatus是10*10零阵从1*1开始,所以用floor函数 ry = floor(ypos);if boardstatus(rx,ry)==1||boardstatus(rx,ry)==2 该位置已经有棋子continue; 回到上面的循环endposflag = 0; 跳出循环endif qishou==1drawthego(xpos,ypos,qishou);boardstatus(rx,ry)=1; 此空为红棋qishou = 0; 轮到黑棋下elsedrawthego(xpos,ypos,qishou);boardstatus(rx,ry)=2; 此空位黑棋qishou = 1; 轮到红棋下endif iswin(boardstatus,rx,ry)==1if qishou==1winmsg = '黑棋连成了五颗,黑棋胜!';elsewinmsg = '红棋连成了五颗,红棋胜!';endif iswin(boardstatus,rx,ry)==2winmsg = '和棋';msgbox(winmsg) msgbox(Message) 创建一个对话框,根据figure窗体大小自动将Message换行。

matlab小游戏课程设计

matlab小游戏课程设计

matlab小游戏课程设计一、课程目标知识目标:1. 学生能理解Matlab的基本操作,包括变量定义、运算符使用和程序流程控制。

2. 学生能够运用Matlab编写简单的交互式小游戏,如猜数字、迷宫等。

3. 学生掌握Matlab中绘图和动画功能,实现对游戏结果的展示。

技能目标:1. 学生培养编程思维,学会运用Matlab解决实际问题。

2. 学生能够运用所学知识,设计并实现具有简单逻辑和交互功能的Matlab小游戏。

3. 学生通过团队协作,提高沟通与协作能力。

情感态度价值观目标:1. 学生培养对计算机编程的兴趣,提高学习积极性。

2. 学生在游戏设计和实现过程中,培养创新精神和实践能力。

3. 学生通过游戏编程,体验团队合作的重要性,树立正确的价值观。

本课程针对高中年级学生,结合Matlab编程知识,以趣味性小游戏为载体,激发学生兴趣,培养编程技能和团队协作能力。

课程要求学生在理解基本编程知识的基础上,动手实践,实现具体的学习成果。

通过本课程的学习,使学生能够更好地掌握Matlab编程技能,提高解决实际问题的能力。

二、教学内容1. Matlab基础知识回顾:变量定义、数据类型、运算符、程序流程控制(条件语句、循环语句)。

2. Matlab绘图与动画:二维绘图、三维绘图、动画制作。

3. 简单交互式小游戏设计:- 猜数字游戏:随机生成一个数字,学生编写程序实现用户输入猜测,程序给出提示的功能。

- 迷宫游戏:设计一个简单迷宫,编写程序实现角色移动、碰撞检测和路径寻找。

4. 团队项目实践:学生分组设计并实现一个Matlab小游戏,要求包含交互、绘图和动画功能。

教学内容安排与进度:第一课时:Matlab基础知识回顾。

第二课时:Matlab绘图与动画。

第三课时:简单交互式小游戏设计(猜数字游戏)。

第四课时:简单交互式小游戏设计(迷宫游戏)。

第五课时:团队项目实践。

本教学内容基于Matlab编程知识,结合课程目标,制定详细的教学大纲。

实验4Matlab程序设计1

实验4Matlab程序设计1

实验4 Matlab程序设计1实验目的:1、掌握建立和执行M文件的方法;2、掌握实现选择结构的方法;3、掌握实现循环结构的方法。

实验内容:1. 从键盘输入一个4位整数,按如下规则加密后输出。

加密规则:每位数字都加上7,然后用和除以10的余数取代该数字;再把第一位与第三位交换,第二位与第四位交换。

2. 求分段函数的值。

2x +x-6, x <0且x式-3y = *x2—5x + 6 0Wxc 5 且x 式2及x 式3X2 _ X -1 其他用if语句实现,分别输出x=-5,-3,0,1,2,2.5,3,5时的y值。

3. 输入一个百分制成绩,要求输出成绩等级A、B、C、D、E,其中90~100分为A,80~89分为B,70~79分为C,60~69分为D,60分以下为E。

要求:(1)分别用if语句和swich语句实现。

(2)输入百分制成绩后要判断该成绩的合理性,对不合理的成绩应输出出错信息。

4. 硅谷公司员工的工资计算方法如下:(1)工作时数超过120小时者,超过部分加发15% ;(2)工作时数低于60小时者,扣发700元;(3)其余按每小时84元计发。

试编程按输入的工号和该号员工的工时数,计算应发工资。

5. 设计程序,完成两位数的加、减、乘、除四则运算。

即:输入两个两位随机整数,再输入一个运算符号,做相应的运算,并显示相应的结果。

6. 建立5X 6矩阵,要求输出矩阵的第n行元素。

当n值超过矩阵的行数时,自动转为输出矩阵的最后一行元素,并给出出错信息。

7. 产生20 个两位随机整数,输出其中小于平均数的偶数。

实验代码及实验结果1.>> a=input(' 请输入一个四位整数:');请输入一个四位整数:9988>> a1=fix(a/1000);>> a2=rem(fix(a/100),10);>> a3=rem(fix(a/10),10);>> a4=rem(a,10);>> a1=rem(a1+7,10);>> a2=rem(a2+7,10);>> a3=rem(a3+7,10);>> a4=rem(a4+7,10);>> b=a1;a1=a3;a3=b;>> b=a2;a2=a4;a4=b;>> c=a1*1000+a2*100+a3*10+a4;>> disp(c)3.>> a=input C请输入一个四位整数:一); 请输人一个四f立整數:3988 »(a/1000);>> a2=ren(fix(a/100), 10);>> a3=ren(fiK(a/10)?10);>> 血(a, ID);» al=re&(al+^ 10);>> a^rsB(a2+7f 10);>> a3=rem(a3+7? 10):>> 丑"“血(M+C 10);>> b=al:a1=a3:a3=b;» b=a2:a2=a4:a4=b,» c-al *100(Hai2*l 0(H-a3*l 0+ttl;>> disp(c)55662.x=input('请输入x的值:');if x<0 & x~=-3y=x92+x-6;elseif x>=0 & x<5 & x~=2 & x~=3y=x.A2+5.*x+6elsey=x.A2-x-1;end请输入孟的値:[-瓦-亠0,1, 2t2. E f 3, 5]7 =29. 0000 IL ODDO -I. 0000 -1.0000 1. OODO 2.7500 5. QOOD(1) if语句:a=i nput('请输入成绩:');ig.ooooif a>=90 & a<=100disp('A');elseif a>=80 & a<90disp('B');elseif a>=70 & a<80disp('C');elseif a>=60 & a<70disp('D');elseif a<60 &a>=0disp('E');elsedisp('输入有误!'); end( 2) switch 语句:a=input(' 请输入成绩:'); switch fix(a/10)case{9}disp('A');case{8}disp('B');case{7}disp('C');case{6}disp('D');case nu m2cell(2:5)disp('E')otherwisedisp('输入有误!');end请输入咸绩:80E请输入咸绩;5E请输入成绩:1212输入有误I»4.n=i nput('请输入工号:’);a=i nput('请输入工作小时数:'); if a>=120 y=a*84+a*84*0.15;elseif a<120 & a>=60y=a*84;elsey=a*84-700;disp(y);end请输入工号:30请输入工作小时数:231232。

matlab编写的贪吃蛇游戏

matlab编写的贪吃蛇游戏

function snake(cmd)global SNAKE WALL LEVEL BOARD DIRECTION RUNNING FOOD BONUS PAUSEif ~nargincmd = 'init';endif ~(ischar(cmd)||isscalar(cmd))return;endswitch cmdcase 'init'scrsz = get(0,'ScreenSize');f = figure('Name','Snake',... %显示图形窗口的标题'Numbertitle','off',... %标题栏中是否显示’Figure No. n’,其中n为图形窗口的编号'Menubar','none',... %转换图形窗口菜单条的“关”'Color',[.95 .95 .95],...'DoubleBuffer','on',...'Position',[(scrsz(3)-400)/2 (scrsz(4)-300)/2 400 300],...'Colormap',[.1 .71 0;.3 .4 .4;0 0 0;1 1 0],...'CloseRequestFcn',sprintf('%s(''Stop'');closereq;',mfilename),...'KeyPressFcn',sprintf('%s(double(get(gcbf,''Currentcharacter'')))',mfilename)); %当在图形窗口中按下一键时,定义一回调程序%建菜单FileMenu = uimenu(f,'Label','&File');uimenu(FileMenu,'Label','NewGame','Accelerator','N','Callback',sprintf('%s(''NewGame'')',mfilename));uimenu(FileMenu,'Label','Exit','Accelerator','Q','Separator','on','Callback',sprintf('%s(''Stop'');close req',mfilename));LevelMenu = uimenu(f,'Label','&Level');uimenu(LevelMenu,'Label','1','Callback',sprintf('%s(''Level'')',mfilename))uimenu(LevelMenu,'Label','2','Callback',sprintf('%s(''Level'')',mfilename))uimenu(LevelMenu,'Label','3','Callback',sprintf('%s(''Level'')',mfilename))uimenu(LevelMenu,'Label','4','Callback',sprintf('%s(''Level'')',mfilename),'checked','on')uimenu(LevelMenu,'Label','5','Callback',sprintf('%s(''Level'')',mfilename))WallMenu = uimenu(f,'Label','&Wall');uimenu(WallMenu,'Label','Nowall','Callback',sprintf('%s(''Wall'')',mfilename),'checked','on')uimenu(WallMenu,'Label','Wall','Callback',sprintf('%s(''Wall'')',mfilename))% Create The axesaxes('Units','normalized',...'Position', [0 0 1 1],...'Visible','off',...'DrawMode','fast',...'NextPlot','replace');%清除图形轴中全部的子对象,并将轴的对象属性设置为系统的默认数值% Add the boardBOARD = image(getTitle,'CDataMapping','scaled');axis imageset(gca,...'XTick',NaN,...'YTick',NaN)text(40,30,'0',...'FontUnits','normalized', ...'FontSize',0.03, ...'FontName','FixedWidth',...'FontWeight','bold',...'Color',[1 1 1],...'VerticalAlignment','baseline', ...'HorizontalAlignment','right',... %标签字符串的对齐方式'Tag','Score'); %用户指定的对象标记符SNAKE = [14,20;14,19;14,18;14,17;14,16];W ALL = zeros(30,40);LEVEL = 4;case 28 % leftif SNAKE(2,2)~=mod(SNAKE(1,2)-2,40)+1DIRECTION = cmd;endcase 29 % rightif SNAKE(2,2)~=mod(SNAKE(1,2),40)+1DIRECTION = cmd;endcase 30 % upif SNAKE(2,1)~=mod(SNAKE(1,1)-2,30)+1DIRECTION = cmd;endcase 31 % downif SNAKE(2,1)~=mod(SNAKE(1,1),30)+1DIRECTION = cmd;endcase 'Level' % Change of Levelset(get(get(gcbo,'Parent'),'Children'),'checked','off')set(gcbo,'checked','on')LEVEL = length(get(gcbo,'Label'));case 'Wall' % Change of Wallset(get(get(gcbo,'Parent'),'Children'),'checked','off')set(gcbo,'checked','on')W ALL = zeros(30,40);switch get(gcbo,'Label')case 'No wall'case 'Wall'W ALL([1 30],:) = 1;W ALL(:,[1 40]) = 1;endfeval(mfilename,'Stop')case 'ShowScore' % Change of Show Scoreswitch get(gcbo,'checked')case 'on'set(gcbo,'checked','off')set(findobj(gcbf,'Tag','Score'),'Visible','off')case 'off'set(gcbo,'checked','on')set(findobj(gcbf,'Tag','Score'),'Visible','on') endcase 'NewGame' % New Game N or Ctrl-Nset(findobj(gcbf,'Tag','Score'),'String','0')SNAKE = [14,20;14,19;14,18;14,17;14,16];DIRECTION = 29; % rightBONUS = 0;PAUSE = false;feval(mfilename,'Food')feval(mfilename,'Start')case 'Start' % Start GameRUNNING = true;bonusCounter = 0;foodCounter = 0;while(RUNNING)if ~PAUSESNAKE = circshift(SNAKE,1);SNAKE(1,:) = SNAKE(2,:);switch DIRECTIONcase 28 % leftSNAKE(1,2) = mod(SNAKE(1,2)-2,40)+1;case 29 % rightSNAKE(1,2) = mod(SNAKE(1,2),40)+1;case 30 % upSNAKE(1,1) = mod(SNAKE(1,1)-2,30)+1;case 31 % downSNAKE(1,1) = mod(SNAKE(1,1),30)+1;end% Check if snake hits any barrierif WALL(SNAKE(1,1),SNAKE(1,2)) || ...sum(ismember(SNAKE(2:end,1),SNAKE(1,1))+...ismember(SNAKE(2:end,2),SNAKE(1,2))==2)pause(.3)delete(findobj(gcbf,'Tag','Bonus'))feval(mfilename,'Stop')set(BOARD,'CData',getGameOver)else% Check if snake eats bonusif isequal(SNAKE(1,:),BONUS)% Update scorescorehandle = findobj(gcbf,'Tag','Score');set(scorehandle,'String',...num2str(LEVEL*ceil(bonusCounter/3)+...str2double(get(scorehandle,'String'))))bonusCounter = 1;endif BONUSbonusCounter = bonusCounter-1;if bonusCounter<=0delete(findobj(gcbf,'Tag','Bonus'))BONUS = 0;endend% Check if snake eats foodif isequal(SNAKE(1,:),FOOD)% Snake Grows!SNAKE(end+1,:) = SNAKE(end,:);% Update scorescorehandle = findobj(gcbf,'Tag','Score');set(scorehandle,'String',...num2str(LEVEL+str2double(get(scorehandle,'String'))))% Spawn new foodfeval(mfilename,'Food')if ~BONUS % only update if no bonus existbonusCounter = bonusCounter+15;foodCounter = foodCounter+1;endif foodCounter==4 % Spawn new bonus every fourth Foodfeval(mfilename,'Bonus')foodCounter = 0;endendfeval(mfilename,'DrawBoard')endendpause(.3/LEVEL)endcase {112 32} % Pause GamePAUSE=~PAUSE;if PAUSE && RUNNINGset(BOARD,'CData',getPause)endcase 'Stop' % Stop GameRUNNING = false;set(BOARD,'CData',getTitle)case 'Food' % Put food onto game boardCData = W ALL;for i=1:size(SNAKE,1)CData(SNAKE(i,1),SNAKE(i,2)) = 1;endind = find(CData'==0);ind = ind(ceil(rand*length(ind)));FOOD = [ceil(ind/40) mod(ind-1,40)+1]; case 'Bonus' % Put bonus onto game board delete(findobj(gcbf,'Tag','Bonus'))CData = W ALL;for i=1:size(SNAKE,1)CData(SNAKE(i,1),SNAKE(i,2)) = 1;endCData(FOOD(1,1),FOOD(1,2)) = 1;ind = find(CData'==0);ind = ind(ceil(rand*length(ind)));BONUS = [ceil(ind/40) mod(ind-1,40)+1];text(BONUS(2),BONUS(1),'\heartsuit',...'Color',[1 0 0],...'FontUnits','normalized',...'FontSize',.065,...'HorizontalAlignment','Center',...'VerticalAlignment','Middle',...'Tag','Bonus')case 'DrawBoard' % Draw the Game Board CData = W ALL;for i=1:size(SNAKE,1)CData(SNAKE(i,1),SNAKE(i,2)) = 2;endCData(FOOD(1),FOOD(2)) = 4;set(BOARD,'CData',CData)endfunction [ico,map]=getIcon()% create simple icon matrixico = ones(13)*3;ico(:,1:4:13) = 1;ico(1:4:13,:) = 1;ico(6:8,6:8) = 2;ico(6:8,10:12) = 2;ico(10:12,10:12) = 2;map = [0 0 0;.5 .5 .6;[148 182 166]/255;];function title = getTitle()title = zeros(30,40);title([42 43 47 48 72 73 77 78 104 105 106 107 108 134 135 136 137 138 ...164 165 166 167 168 222 223 224 225 226 227 228 252 253 254 255 256 ...257 258 282 283 312 313 344 345 346 347 348 374 375 376 377 378 404 ...405 406 407 408 464 465 466 494 495 496 522 523 527 528 552 553 557 ...558 582 583 587 588 612 613 614 615 616 617 618 642 643 644 645 646 ...647 648 672 673 674 675 676 677 678 727 728 729 730 731 732 733 734 ...735 736 737 738 757 758 759 760 761 762 763 764 765 766 767 768 787 ...788 789 790 791 792 793 794 795 796 797 798 824 825 826 854 855 856 ...882 883 887 888 912 913 917 918 972 973 974 975 976 977 978 1002 ...1003 1004 1005 1006 1007 1008 1032 1033 1037 1038 1062 1063 1067 ...1068 1092 1093 1097 1098 1122 1123 1124 1125 1126 1152 1153 1154 ...1155 1156]) = 3;function gameover = getGameOver()gameover = zeros(30,40);gameover([95 96 97 98 99 100 101 102 103 104 109 110 111 112 113 114 ...125 126 127 128 129 130 131 132 133 134 139 140 141 142 143 144 155 ...156 163 164 167 168 175 176 185 186 193 194 197 198 205 206 215 216 ...219 220 221 222 223 224 229 230 231 232 233 234 245 246 249 250 251 ...252 253 254 259 260 261 262 263 264 335 336 337 338 339 340 341 342 ...343 344 347 348 349 350 351 352 353 354 365 366 367 368 369 370 371 ...372 373 374 377 378 379 380 381 382 383 384 395 396 399 400 415 416 ...425 426 429 430 445 446 455 456 457 458 459 460 461 462 463 464 467 ...468 469 470 471 472 473 474 485 486 487 488 489 490 491 492 493 494 ...497 498 499 500 501 502 503 504 575 576 577 578 579 580 581 582 583 ...584 587 588 589 590 591 592 593 594 595 596 605 606 607 608 609 610 ...611 612 613 614 617 618 619 620 621 622 623 624 625 626 635 636 647 ...648 651 652 655 656 665 666 677 678 681 682 685 686 695 696 697 698 ...699 700 701 702 703 704 707 708 711 712 715 716 725 726 727 728 729 ...730 731 732 733 734 737 738 741 742 745 746 755 756 785 786 817 818 ...819 820 821 822 823 824 827 828 829 830 831 832 833 834 835 836 847 ...848 849 850 851 852 853 854 857 858 859 860 861 862 863 864 865 866 ...887 888 891 892 917 918 921 922 935 936 937 938 939 940 941 942 943 ...944 949 950 953 954 955 956 965 966 967 968 969 970 971 972 973 974 ...979 980 983 984 985 986 995 996 999 1000 1003 1004 1025 1026 1029 ...1030 1033 1034 1055 1056 1059 1060 1063 1064 1067 1068 1069 1070 ...1071 1072 1075 1076 1085 1086 1093 1094 1097 1098 1099 1100 1101 ...1102 1105 1106]) = 1;function pause = getPause()pause = zeros(30,40);pause([41 42 43 44 45 46 47 48 49 50 71 72 73 74 75 76 77 78 79 80 101 ...102 103 104 105 106 107 108 109 110 131 132 136 137 161 162 166 167 ...193 194 195 223 224 225 283 284 285 313 314 315 341 342 346 347 371 ...372 376 377 401 402 406 407 431 432 433 434 435 436 437 461 462 463 ...464 465 466 467 491 492 493 494 495 496 497 551 552 553 554 555 556 ...581 582 583 584 585 586 616 617 646 647 671 672 673 674 675 676 677 ...701 702 703 704 705 706 707 731 732 733 734 735 736 737 791 792 796 ...797 821 822 826 827 853 854 855 856 857 883 884 885 886 887 913 914 ...915 916 917 971 972 973 974 975 976 977 1001 1002 1003 1004 1005 ...1006 1007 1031 1032 1036 1037 1061 1062 1066 1067 1091 1092 1096 ...1097 1121 1122 1123 1124 1125 1151 1152 1153 1154 1155]) = 1;。

matlab编的五子棋

matlab编的五子棋

%五子棋程序function [ ] = five()global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha sshf=figure('resize','off','name','five',...'position',[360 280 560 420],'numbertitle','off');ha=axes;set(gcf,'menubar','none','color',[ ])set(gca,'position',[ ])set(gca,'xlim',[0,9],'ylim',[0,9])set(ha,'xtick',[],'ytick',[],'box','on')set(ha,'color',[ ,])set(ha,'DataAspectRatio',[1 1 1],'PlotBoxAspectRatio',[1 1 1])x=repmat([0;9],1,9);y=[1:9;1:9];line(x,y,'color','k')line(y,x,'color','k')hst=uicontrol('style','text','string','Score','fontsize',30,...'units','normal','position',[,,,],'parent',hf,...'ForegroundColor','w','backgroundcolor',[ ],...'fontweight','bold');hsc=uicontrol('style','text','string','0','fontsize',24,...'units','normal','position',[,,,],'parent',hf,...'ForegroundColor','w','backgroundcolor',[ ],...'fontweight','bold');hbt=uicontrol('style','pushbutton','string','Restart','fontsize',18,. ..'units','normal','position',[,,,],'parent',hf,...'fontweight','bold','callback',@restart);color=[...1 1 0;1 0 1;0 1 1;1 0 0;0 1 0;0 0 1;0;];h1=annotation('ellipse',[,,,],'facecolor','k');h2=annotation('ellipse',[,,,],'facecolor','k');h3=annotation('ellipse',[,,,],'facecolor','k');set(ha,'buttondownfcn',@select2)initializefunction initialize()global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ss a=zeros(9);h=zeros(9)*NaN;m1=[];n1=[];m2=[];n2=[];score=0;ss=0;k=rs(1:81,5);t=ceil(rand(1,5)*7);a(k)=t;[m,n] = ind2sub([9,9],k);y=;x=;for p=1:5h(k(p))=line(x(p),y(p),'marker','o','markersize',24,...'markerfacecolor',color(t(p),:),'markeredgecolor','none',... 'buttondownfcn',@select1);endt=ceil(rand(1,3)*7);set(h1,'facecolor',color(t(1),:))set(h2,'facecolor',color(t(2),:))set(h3,'facecolor',color(t(3),:))function [k]=rs(s,n);for m=1:nt=ceil(rand*length(s));k(m)=s(t);s(t)=[];endfunction select1(src,eventdata)global a h m1 n1n1=ceil(get(src,'xdata'));m1=ceil(9-get(src,'ydata'));set(h(~isnan(h)),'markeredgecolor','none')set(src,'markeredgecolor','w')function select2(src,eventdata)global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ssif isempty(m1) || isempty(n1)returnendcp=get(src,'currentpoint');n2=ceil(cp(1,1));m2=ceil(9-cp(1,2));if a(m2,n2)returnendb=~a;b(m1,n1)=1;b=bwlabel(b,4);if b(m1,n1)~=b(m2,n2)returnenda(m2,n2)=a(m1,n1);a(m1,n1)=0;h(m2,n2)=h(m1,n1);h(m1,n1)=NaN;set(h(m2,n2),'xdata',,'ydata',,'markeredgecolor','none') m1=[];n1=[];judgement;if sum(sum(~a))<3hgo=text(1,,'Game Over','fontsize',36,'fontweight',... 'bold','parent',src);pause(3)delete(hgo);delete(h(~isnan(h)))set(hsc,'string','0')initialize;returnendif ~ssnew;endfunction judgementglobal a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ss b=logical(zeros(9,9));ss=0;left=0;right=0;up=0;down=0;lu=0;rd=0;ld=0;ru=0;while n2-left-1>0 && a(m2,n2-left-1)==a(m2,n2)left=left+1;endwhile n2+right+1<10 && a(m2,n2+right+1)==a(m2,n2)right=right+1;endwhile m2-up-1>0 && a(m2-up-1,n2)==a(m2,n2)up=up+1;endwhile m2+down+1<10 && a(m2+down+1,n2)==a(m2,n2)down=down+1;endwhile n2-lu-1>0 && m2-lu-1>0 && a(m2-lu-1,n2-lu-1)==a(m2,n2) lu=lu+1;endwhile n2+rd+1<10 && m2+rd+1<10 && a(m2+rd+1,n2+rd+1)==a(m2,n2) rd=rd+1;endwhile n2-ld-1>0 && m2+ld+1<10 && a(m2+ld+1,n2-ld-1)==a(m2,n2) ld=ld+1;endwhile n2+ru+1<10 && m2-ru-1>0 && a(m2-ru-1,n2+ru+1)==a(m2,n2) ru=ru+1;endif left+right+1>=5b(m2,n2-left:n2+right)=1;endif up+down+1>=5b(m2-up:m2+down,n2)=1;endif lu+rd+1>=5ind=sub2ind([9,9],m2-lu:m2+rd,n2-lu:n2+rd);b(ind)=1;endif ld+ru+1>=5ind=sub2ind([9,9],m2+ld:-1:m2-ru,n2-ld:n2+ru);b(ind)=1;endif sum(sum(b))a(b)=0;delete(h(b));h(b)=NaN;score=score+sum(sum(b));set(hsc,'string',num2str(score))ss=1;endfunction newglobal a h m1 n1 m2 n2 t h1 h2 h3 color score hsc hak=rs(find(~a),3);a(k)=t;[mt,nt] = ind2sub([9,9],k);y=;x=;for p=1:3h(k(p))=line(x(p),y(p),'marker','o','markersize',24,...'markerfacecolor',color(t(p),:),'markeredgecolor','none',... 'buttondownfcn',@select1);endfor p=1:3m2=mt(p);n2=nt(p);judgement;endif sum(sum(~a))==0hgo=text(1,,'Game Over','fontsize',36,'fontweight',... 'bold','parent',ha);pause(3)delete(hgo);delete(h(~isnan(h)))set(hsc,'string','0')initialize;returnendt=ceil(rand(1,3)*7);set(h1,'facecolor',color(t(1),:))set(h2,'facecolor',color(t(2),:))set(h3,'facecolor',color(t(3),:))function restart(src,eventdata)global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ss delete(h(~isnan(h)))set(hsc,'string','0')initialize;。

matlab扫雷代码讲解

matlab扫雷代码讲解

matlab扫雷代码讲解扫雷游戏是一个经典的逻辑游戏,其中玩家需要使用鼠标点击方块以揭示其下方的数字。

数字表示周围的方块中有多少个地雷。

如果玩家揭示了一个地雷,游戏就会结束。

以下是一个简单的MATLAB 扫雷游戏的代码示例:matlab复制代码:% 初始化游戏function minesweeper()% 初始化一个10x10 的网格,其中一些方块包含地雷(用'b' 表示)board = zeros(10,10);board(randperm(100,15)) = 'b'; % 在随机位置放置地雷while true% 显示当前的游戏板board% 等待玩家输入waitforbuttonpress;% 如果玩家点击了一个地雷,显示一个消息并结束游戏if board(ginput(1)) == 'b'disp('Game Over!');break;endendend代码解释:1.board = zeros(10,10);:初始化一个10x10 的网格,其中所有的方块都是空的(用 0 表示)。

2.board(randperm(100,15)) = 'b';:在随机位置放置15 个地雷。

randperm(100,15) 生成一个包含 1 到100 的随机排列的数组,该数组有15 个元素。

这意味着地雷被放置在位置1, 2, ..., 15, 26, ..., 96, 97, ..., 100。

3.while true:无限循环,直到玩家点击一个地雷。

4.board:显示当前的游戏板。

在MATLAB 中,你可以使用 board 来显示一个变量,它会自动创建一个图形窗口来显示该变量。

5.waitforbuttonpress;:等待玩家输入。

这会暂停程序的执行,直到玩家按下一个键或鼠标按钮。

6.if board(ginput(1)) == 'b':检查玩家点击的方块是否包含地雷。

有趣的MATLAB1.游戏程序

有趣的MATLAB1.游戏程序

有趣的MATLAB1.游戏程序MATLAB游戏程序目录1.空格游戏 (2)2.华容道 (3)3.凑五子棋 (14)4.2048 (19)5.俄罗斯方块 (24)1.空格游戏function pintu1()A = gen();G = [1 2 3;4 5 6;7 8 0];drawmap(A);while 1[xpos,ypos] = ginput(1);col = ceil(xpos);row = 3-ceil(ypos)+1;num = A(row,col);if row>1&A(row-1,col)==0A(row-1,col) = num;A(row,col) = 0;endif row<3&A(row+1,col)==0A(row+1,col) = num;A(row,col) = 0;endif col>1&A(row,col-1)==0A(row,col-1) = num;A(row,col) = 0;endif col<3&A(row,col+1)==0A(row,col+1) = num;A(row,col) = 0;enddrawmap(A)zt = abs(A-G);if sum(zt(:))==0msgbox('恭喜您成功完成!')breakendendfunction drawmap(A)clf;hold online([0 3],[0 0],'linewidth',4);line([3 3],[0 3],'linewidth',4);line([0 3],[3 3],'linewidth',4);line([0 0],[0 3],'linewidth',4);for i = 1:3for j = 1:3drawrect([j-1 3-i],[j 3-i],[j 3-i+1],[j-1 3-i+1],'y',A(i,j)); endendaxis equalaxis offfunction drawrect(x1,x2,x3,x4,color,num)x = [x1(1) x2(1) x3(1) x4(1)];y = [x1(2) x2(2) x3(2) x4(2)];fill(x,y,color)if num==0text(0.5*(x1(1)+x2(1)),0.5*(x1(2)+x4(2)),' ','fontsize',24)elsetext(0.5*(x1(1)+x2(1))-0.05,0.5*(x1(2)+x4(2)),num2str(num),'fontsize',24) endfunction y = gen()y = inf*ones(1,9);for i = 1:9while 1a = randint(1,1,9);if isempty(find(y==a))y(i) = a;breakendendendy = reshape(y,3,3);2.华容道function huarongdao()A = [2 1 1 3;2 1 1 3;4 6 6 5;4 7 7 5;7 0 0 7];drawmap(A)while 1if A(5,2)==1&A(5,3)==1ch = menu('曹操成功逃出华容道!如果要继续玩,按“是”,否则按“否”','是','否');switch chcase 1huarongdao();case 2returnendend[xpos,ypos] = ginput(1);col = ceil(xpos);row = 5-ceil(ypos)+1;juese = A(row,col);switch juesecase 1%点击了曹操[I,J] = find(A==1);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0]) A([rn,rm],ln-1)=[1;1];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0]) A([rn,rm],lm+1)=[1;1];A([rn,rm],ln)=[0;0];drawmap(A)end%判断是否能向下移if rn>1&isequalm(A(rn-1,[ln,lm]),[0,0]) A(rn-1,[ln,lm])=[1,1];A(rn+1,[ln,lm])=[0,0];drawmap(A)end%判断是否能向上移if rm<5&isequalm(A(rm+1,[ln,lm]),[0,0]) A(rm+1,[ln,lm])=[1,1];A(rm-1,[ln,lm])=[0,0];drawmap(A)endcase 2% 点击了黄忠[I,J] = find(A==2);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0]) A([rn,rm],ln-1)=[2;2];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0]) A([rn,rm],lm+1)=[2;2];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 2;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm+1,ln) = 2;A(rm-1,ln) = 0;drawmap(A)endelse%只能上移A(rn-1,ln) = 2;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 2;A(rm-1,ln) = 0;drawmap(A)endcase 3%张飞[I,J] = find(A==3);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0])A([rn,rm],ln-1)=[3;3];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0])A([rn,rm],lm+1)=[3;3];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 3;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm+1,ln) = 3;A(rm-1,ln) = 0;endelse%只能上移A(rn-1,ln) = 3;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 3;A(rm-1,ln) = 0;endcase 4%马超[I,J] = find(A==4);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0])A([rn,rm],ln-1)=[4;4];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0])A([rn,rm],lm+1)=[4;4];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 4;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm+1,ln) = 4;endelse%只能上移A(rn-1,ln) = 4;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 4;A(rm-1,ln) = 0;drawmap(A)endcase 5%赵云[I,J] = find(A==5);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0]) A([rn,rm],ln-1)=[5;5];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0]) A([rn,rm],lm+1)=[5;5];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 5;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm-1,ln) = 0;drawmap(A)endelse%只能上移A(rn-1,ln) = 5;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 5;A(rm-1,ln) = 0;drawmap(A)endcase 6%关羽[I,J] = find(A==6);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向上移if rn>1 & isequalm(A(rn-1,[ln,lm]),[0,0])A(rn-1,[ln,lm])=[6,6];A(rn,[ln,lm])=[0,0];drawmap(A)end%判断是否能向下移if rm<5&isequalm(A(rm+1,[ln,lm]),[0,0])A(rm+1,[ln,lm])=[6,6];A(rm,[ln,lm])=[0,0];drawmap(A)endif ln>1&A(rn,ln-1)==0if lm<4&A(rm,lm+1)==0%如果又能左移又能右移,则要点击的部位ch = menu('请选择移到的方向:','左','右')switch chcase 1%左移A(rm,ln-1) = 6;A(rm,ln+1) = 0;drawmap(A)case 2%右移A(rm,lm+1) = 6;A(rm,lm-1) = 0;drawmap(A)endelse%只能左移A(rm,ln-1) = 6;A(rm,ln+1) = 0;drawmap(A)endelseif lm<4&A(rm,lm+1)==0A(rm,lm+1) = 6;A(rm,lm-1) = 0;drawmap(A)endcase 7 %小卒if row>1&A(row-1,col)==0 % 上if col>1&A(row,col-1)==0 % 左ch = menu('请选择移到的方向:','上','左') switch chcase 1A(row-1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col-1) = 7;A(row,col) = 0;drawmap(A)endelseif row<5&A(row+1,col)==0% 下ch = menu('请选择移到的方向:','上','下') switch chcase 1A(row-1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row+1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col<4&A(row,col+1)==0 %右switch chcase 1A(row-1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endelse %只能向上A(row-1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col>1&A(row,col-1)==0%左if row<5&A(row+1,col)==0%下ch = menu('请选择移到的方向:','左','下') switch chcase 1A(row,col-1) = 7;A(row,col) = 0;drawmap(A)case 2A(row+1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col<4&A(row,col+1)==0%右switch chcase 1A(row,col-1) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endelse%只能向左A(row,col-1) = 7;A(row,col) = 0;drawmap(A)endelseif row<5&A(row+1,col)==0%下if col<4&A(row,col+1)==0%右ch = menu('请选择移到的方向:','下','右') switch chcase 1A(row+1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endelse%只能向下A(row+1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col<4&A(row,col+1)==0%只能向右A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endendendfunction drawmap(A)clfhold on%曹操[I J] = find(A==1);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'r')text(0.5*(x1+x2)-0.5,0.5*(y1+y2),'曹操','fontsize',28)% 黄忠[I,J] = find(A==2);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'黄','fontsize',28)text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'忠','fontsize',28) % 张飞[I,J] = find(A==3);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'张','fontsize',28) text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'飞','fontsize',28) % 马超[I,J] = find(A==4);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'马','fontsize',28) text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'超','fontsize',28) % 赵云[I,J] = find(A==5);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'赵','fontsize',28) text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'云','fontsize',28) % 关羽[I,J] = find(A==6);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+0.5*(x1+x2))-0.26,0.5*(y1+y2),'关','fontsize',28) text(0.5*(0.5*(x1+x2)+x2)-0.26,0.5*(y1+y2),'羽','fontsize',28) %小卒[I,J] = find(A==7);for i = 1:length(I)x1 = J(i)-1;x2 = J(i);y1 = 5-(I(i)-1);y2 = 5-I(i);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'g')text(0.5*(x1+x2)-0.26,0.5*(y1+y2),'卒','fontsize',28)end% 画背景line([0 4],[0 0],'color','b','linewidth',4)line([0 4],[5 5],'color','b','linewidth',4)line([0 0],[0 5],'color','b','linewidth',4)line([4 4],[0 5],'color','b','linewidth',4)for i = 1:4line([0 4],[i i],'color','b','linestyle','--')endfor i = 1:3line([i i],[0 5],'color','b','linestyle','--')endaxis equalaxis([0 4 0 5])axis offfunction drawrect(x1,x2,x3,x4,color)x = [x1(1) x2(1) x3(1) x4(1)];y = [x1(2) x2(2) x3(2) x4(2)];fill(x,y,color)3.凑五子棋function [ ] = five()global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha sshf=figure('resize','off','name','five',...'position',[360 280 560 420],'numbertitle','off');set(gcf,'menubar','none','color',[0.3 0.3 0.3])set(gca,'position',[0.2300 0.1100 0.7750 0.8150]) set(gca,'xlim',[0,9],'ylim',[0,9])set(ha,'xtick',[],'ytick',[],'box','on')set(ha,'color',[0.7 0.6,0.6])set(ha,'DataAspectRatio',[1 1 1],'PlotBoxAspectRatio',[1 1 1]) x=repmat([0;9],1,9);y=[1:9;1:9];line(x,y,'color','k')line(y,x,'color','k')hst=uicontrol('style','text','string','Score','fontsize',30,...'units','normal','position',[0.02,0.55,0.26,0.14],'parent',hf,...'ForegroundColor','w','backgroundcolor',[0.3 0.3 0.3],...'fontweight','bold');hsc=uicontrol('style','text','string','0','fontsize',24,...'units','normal','position',[0.02,0.4,0.26,0.14],'parent',hf,...'ForegroundColor','w','backgroundcolor',[0.3 0.3 0.3],...'fontweight','bold');hbt=uicontrol('style','pushbutton','string','Restart','fontsize',1 8,...'units','normal','position',[0.02,0.16,0.26,0.14],'parent',hf,... 'fontweight','bold','callback',@restart);color=[...1 1 0;1 0 1;0 1 1;1 0 0;0 1 0;0 0 1;0.7 0.3 0;];h1=annotation('ellipse',[0.04,0.84,0.06,0.08],'facecolor','k'); h2=annotation('ellipse',[0.12,0.84,0.06,0.08],'facecolor','k'); h3=annotation('ellipse',[0.2,0.84,0.06,0.08],'facecolor','k'); set(ha,'buttondownfcn',@select2)initializefunction initialize()global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ssa=zeros(9);h=zeros(9)*NaN;m1=[];n1=[];m2=[];n2=[];ss=0;k=rs(1:81,5);t=ceil(rand(1,5)*7);a(k)=t;[m,n] = ind2sub([9,9],k);y=9.5-m;x=n-0.5;for p=1:5h(k(p))=line(x(p),y(p),'marker','o','markersize',24,...'markerfacecolor',color(t(p),:),'markeredgecolor','none',... 'buttondownfcn',@select1);endt=ceil(rand(1,3)*7);set(h1,'facecolor',color(t(1),:))set(h2,'facecolor',color(t(2),:))set(h3,'facecolor',color(t(3),:))function [k]=rs(s,n);for m=1:nt=ceil(rand*length(s));k(m)=s(t);s(t)=[];endfunction select1(src,eventdata)global a h m1 n1n1=ceil(get(src,'xdata'));m1=ceil(9-get(src,'ydata'));set(h(~isnan(h)),'markeredgecolor','none')set(src,'markeredgecolor','w')function select2(src,eventdata)global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ss if isempty(m1) || isempty(n1)returnendcp=get(src,'currentpoint');n2=ceil(cp(1,1));m2=ceil(9-cp(1,2));if a(m2,n2)returnendb=~a;b(m1,n1)=1;b=bwlabel(b,4);if b(m1,n1)~=b(m2,n2)enda(m2,n2)=a(m1,n1);a(m1,n1)=0;h(m2,n2)=h(m1,n1);h(m1,n1)=NaN;set(h(m2,n2),'xdata',n2-0.5,'ydata',9.5-m2,'markeredgecolor','none') m1=[];n1=[];judgement;if sum(sum(~a))<3hgo=text(1,4.5,'Game Over','fontsize',36,'fontweight',...'bold','parent',src);pause(3)delete(hgo);delete(h(~isnan(h)))set(hsc,'string','0')initialize;returnendif ~ssnew;endfunction judgementglobal a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ssb=logical(zeros(9,9));ss=0;left=0;right=0;up=0;down=0;lu=0;rd=0;ld=0;ru=0;while n2-left-1>0 && a(m2,n2-left-1)==a(m2,n2)left=left+1;endwhile n2+right+1<10 && a(m2,n2+right+1)==a(m2,n2)right=right+1;endwhile m2-up-1>0 && a(m2-up-1,n2)==a(m2,n2)up=up+1;endwhile m2+down+1<10 && a(m2+down+1,n2)==a(m2,n2) down=down+1;endwhile n2-lu-1>0 && m2-lu-1>0 && a(m2-lu-1,n2-lu-1)==a(m2,n2) lu=lu+1;endwhile n2+rd+1<10 && m2+rd+1<10 && a(m2+rd+1,n2+rd+1)==a(m2,n2) rd=rd+1;endwhile n2-ld-1>0 && m2+ld+1<10 && a(m2+ld+1,n2-ld-1)==a(m2,n2) ld=ld+1;endwhile n2+ru+1<10 && m2-ru-1>0 && a(m2-ru-1,n2+ru+1)==a(m2,n2) ru=ru+1;endif left+right+1>=5b(m2,n2-left:n2+right)=1;endif up+down+1>=5b(m2-up:m2+down,n2)=1;endif lu+rd+1>=5ind=sub2ind([9,9],m2-lu:m2+rd,n2-lu:n2+rd);b(ind)=1;endif ld+ru+1>=5ind=sub2ind([9,9],m2+ld:-1:m2-ru,n2-ld:n2+ru);b(ind)=1;endif sum(sum(b))a(b)=0;delete(h(b));h(b)=NaN;score=score+sum(sum(b));set(hsc,'string',num2str(score))ss=1;endfunction newglobal a h m1 n1 m2 n2 t h1 h2 h3 color score hsc hak=rs(find(~a),3);a(k)=t;[mt,nt] = ind2sub([9,9],k);y=9.5-mt;x=nt-0.5;for p=1:3h(k(p))=line(x(p),y(p),'marker','o','markersize',24,...'markerfacecolor',color(t(p),:),'markeredgecolor','none',... 'buttondownfcn',@select1);endfor p=1:3m2=mt(p);n2=nt(p);judgement;endif sum(sum(~a))==0hgo=text(1,4.5,'Game Over','fontsize',36,'fontweight',... 'bold','parent',ha);pause(3)delete(hgo);delete(h(~isnan(h)))set(hsc,'string','0')initialize;returnendt=ceil(rand(1,3)*7);set(h1,'facecolor',color(t(1),:))set(h2,'facecolor',color(t(2),:))set(h3,'facecolor',color(t(3),:))function restart(src,eventdata)global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ssdelete(h(~isnan(h)))set(hsc,'string','0')initialize;4.2048function g2048(action)global totalscore flag score_board if nargin<1figure_h=figure;set(figure_h,'Units','points')set(figure_h,'UserData',figure_h); totalscore=0;flag=0;score_board=zeros(1,16);action='initialize';endswitch action。

matlab贪吃蛇课程设计

matlab贪吃蛇课程设计

matlab贪吃蛇课程设计一、课程目标知识目标:1. 学生理解MATLAB编程基础,掌握基本语法和编程技巧;2. 学生掌握贪吃蛇游戏的逻辑和规则;3. 学生了解如何在MATLAB中实现图形用户界面(GUI)。

技能目标:1. 学生能够运用MATLAB编写简单的贪吃蛇游戏程序;2. 学生能够运用条件语句和循环语句实现游戏逻辑;3. 学生能够利用MATLAB绘制游戏界面,实现人机交互。

情感态度价值观目标:1. 学生培养对编程的兴趣,增强学习计算机科学的自信心;2. 学生培养团队协作精神和解决问题的能力;3. 学生通过编程实践,认识到编程在现实生活中的应用价值。

课程性质:本课程为实践性较强的课程,旨在让学生通过编写贪吃蛇游戏程序,掌握MATLAB编程技能,并培养实际操作能力。

学生特点:学生为初中年级,具备一定的计算机操作基础,对编程有一定兴趣,但编程经验有限。

教学要求:课程要求教师在讲解编程知识的同时,注重引导学生动手实践,关注个体差异,激发学生的学习兴趣,培养其编程思维和解决问题的能力。

通过课程目标的实现,使学生具备实际编程能力,并为后续计算机科学学习打下基础。

二、教学内容1. MATLAB基础知识:- MATLAB简介与安装;- MATLAB基本操作与界面;- 变量与数据类型;- 基本运算符与表达式;- 简单的输入输出。

2. MATLAB编程技巧:- 选择结构(if-else-end);- 循环结构(for、while);- 函数的定义与调用;- 数组与矩阵操作。

3. 贪吃蛇游戏编程:- 游戏规则与逻辑;- 创建游戏窗口;- 绘制蛇与食物;- 控制蛇的移动;- 碰撞检测与游戏结束条件;- 游戏分数与计时。

4. 图形用户界面(GUI)设计:- GUI基础概念;- 使用GUIDE工具箱设计GUI;- 添加控件与回调函数;- 贪吃蛇游戏GUI设计实践。

教学内容安排与进度:- 第一课时:MATLAB基础知识学习;- 第二课时:MATLAB编程技巧学习;- 第三课时:贪吃蛇游戏规则与逻辑讲解;- 第四课时:贪吃蛇游戏编程实践;- 第五课时:图形用户界面(GUI)设计;- 第六课时:贪吃蛇游戏GUI设计实践。

matlab各种游戏编程大全-俄罗斯方块-贪吃蛇-拼图-五子棋-黑白棋-华容道等

matlab各种游戏编程大全-俄罗斯方块-贪吃蛇-拼图-五子棋-黑白棋-华容道等

用matlab编写的俄罗斯方块小游戏•function RussiaBlock( varargin )if nargin == 0OldHandle = findobj( 'Type', 'figure', 'Tag', 'RussiaBlock' ) ;if ishandle( OldHandle )delete( OldHandle ) ;endFigureHandle = figure( 'Name', '俄罗斯方块MATLAB版', 'Tag', 'RussiaBlock', 'NumberTitle', 'off',...'Menubar', 'none', 'DoubleBuffer', 'on', 'Resize', 'off', 'visible', 'on',...'KeyPressFcn', 'RussiaBlock( ''KeyPress_Callback'', gcbo )',...'HelpFcn', 'helpdlg(''帮不了你- -!'',''不好意思'')',...'CloseRequestFcn', 'RussiaBlock( ''CloseFigure_Callback'', gcbo )' ) ;generate_FigureContent( FigureHandle ) ;init_FigureContent( FigureHandle ) ;set( FigureHandle, 'Visible', 'on' ) ;elseif ischar( varargin{1} )feval( varargin{:} ) ;end% -------------------------------------------------------------------------function generate_FigureContent( FigureHandle )TabSpace = 30 ;BlockWidth = 20 ;BlockHeight = 20 ;FigureWidth = BlockWidth * (12 + 1) + TabSpace * 7;FigureHeight = 500 ;set( FigureHandle, 'Position', [0 0 FigureWidth FigureHeight] ) ;movegui( FigureHandle, 'center' ) ;% 创建菜单BeginMenu = uimenu( FigureHandle, 'Label', '开始' ) ;StartMenu = uimenu( BeginMenu, 'Label', '开始新游戏', 'Accelerator', 'N',...'Callback', 'RussiaBlock( ''StartNewGame_Callback'', gcbo )');SaveMenu = uimenu( BeginMenu, 'Label', '保存', 'Accelerator', 'S', 'Enable', 'off',...'Separator', 'on', 'Cal', 'RussiaBlock( ''SaveGame_Callback'', gcbo )' );LoadMenu = uimenu( BeginMenu, 'Label', '读取', 'Accelerator', 'L', 'Enable', 'off',...'Cal', 'RussiaBlock( ''LoadGame_Callback'', gcbo )' );QuitMenu = uimenu( BeginMenu, 'Label', '退出', 'Accelerator', 'Q', 'Separator', 'on', 'Cal', 'close(gcf)');OperationMenu = uimenu( FigureHandle, 'Label', '功能' );BoardConfigMenu = uimenu( OperationMenu, 'label', '键盘设置', 'Enable', 'off',...'Cal', 'RussiaBlock( ''BoardConfig_Callback'', gcbo )' );FigureConfigMenu = uimenu( OperationMenu, 'label', '界面设置', 'Enable', 'off',...'Cal', 'RussiaBlock( ''FigureConfig_Callback'', gcbo )' );HighScoreMenu = uimenu( OperationMenu, 'label', '最高记录', 'Separator', 'on',...'Cal', 'RussiaBlock( ''HighScore_Callback'', gcbo )', 'Enable', 'off' ); GameLevelMenu = uimenu( OperationMenu, 'Label', '游戏难度',...'Cal','RussiaBlock( ''GameLevel_Callback'', gcbo )' );HelpMenu = uimenu( FigureHandle, 'Label', '帮助' );AboutMenu = uimenu( HelpMenu, 'Label', '关于此软件', 'Cal', 'helpdlg(''俄罗斯方块MATLAB版'',''关于此软件…………'')');HelpDlgMenu = uimenu( HelpMenu, 'Label', '游戏帮助', 'Separator', 'on', 'Cal', 'helpdlg(''帮不了你- -!'',''不好意思'')' );% 创建工具条,图标可以用imread从图片读取,但图片不要太大BeginTool = uipushtool( 'ToolTipString', '开始', 'CData', rand(16,16,3), 'Tag', 'BeginTool',... 'ClickedCallback', 'RussiaBlock( ''StartNewGame_Callback'', gcbo )' ) ;PauseTool = uitoggletool( 'ToolTipString', '暂停', 'Tag', 'PauseTool', 'Tag', 'PauseTool',... 'CData', reshape( repmat( [1 1 0], 16, 16), [16,16,3] ),...'ClickedCallback', 'RussiaBlock( ''PauseGame_Callback'', gcbo )' ) ;% 创建游戏窗口MainWindowXPos = TabSpace;MainWindowYPos = TabSpace;MainWindowWidth = BlockWidth * 12 ;MainWindowHeight = BlockHeight * 22 ;MainWindowPosition = [MainWindowXPos MainWindowYPos MainWindowWidth MainWindowHeight] ;% 定义游戏窗口的右键菜单AxesContextMenu = uicontextmenu( 'Tag', 'uicontextmenu' ) ;uimenu( AxesContextMenu, 'Label', '设置窗口颜色', 'Cal','RussiaBlock( ''WindowColor_Callback'', gcbo )' )uimenu( AxesContextMenu, 'Label', '设置背景图片', 'Cal','RussiaBlock( ''WindowPicture_Callback'', gcbo )' )uimenu( AxesContextMenu, 'Label', '设置方块颜色', 'Cal','RussiaBlock( ''BlockColor_Callback'', gcbo )' )uimenu( AxesContextMenu, 'Label', '恢复默认', 'Cal', 'RussiaBlock( ''Default_Callback'',gcbo )' )MainAxes = axes( 'Units', 'pixels', 'Pos', MainWindowPosition, 'XTick', [], 'YTick',[],'XTickLabel', [],...'YTickLabel', [], 'Box', 'on', 'Tag', 'MainAxes', 'UicontextMenu', AxesContextMenu,...'XLim', [0 MainWindowWidth], 'YLim', [0 MainWindowHeight] ) ;hold on;% 创建一个窗口用于显示下一个方块的图形NextBlockWndXPos = MainWindowXPos + MainWindowWidth + TabSpace ; NextBlockWndHeight = 4 * TabSpace + BlockHeight ;NextBlockWndYPos = MainWindowYPos + MainWindowHeight - NextBlockWndHeight ; NextBlockWndWidth = TabSpace * 4 + BlockWidth ;NextBlockWndPosition = [NextBlockWndXPos NextBlockWndYPos NextBlockWndWidth NextBlockWndHeight] ;NextBlockAxes = axes( 'Units', 'pixels', 'Pos', NextBlockWndPosition, 'XTick', [], 'YTick',[],... 'XTickLabel', [], 'YTickLabel', [], 'XLim', [0 NextBlockWndWidth],...'YLim', [0 NextBlockWndHeight], ...'Box', 'on', 'Tag', 'NextBlockAxes', 'Color', [0.85 0.85 0.85] ) ;% 创建一组控件,包括(两个文本框用于显示当前方块数和成绩,两个按钮用于暂停和退出)ButtonTag = { 'QuitButton', 'PauseButton', 'BlockNumText', 'ScoreText' } ;ButtonStyle = { 'pushbutton', 'togglebutton', 'text', 'text' } ;FontColor = { [0 0 0], [1 0 0], [0 0 1], [1 0 1] } ;ButtonColor = { [0.7 0.8 0.9], [0.3 1 0.3], [0.5 1 1], [0.5 1 1] } ;ButtonString = { '退出', '暂停', '方块数', '积分' };ButtonCallback = { 'close(gcf)', 'RussiaBlock( ''ButtonPauseGame_Callback'', gcbo )', '', '' } ; ButtonNumber = length( ButtonTag ) ;ButtonWidth = NextBlockWndWidth ;ButtonHeight = 50 ;ButtonXPos = NextBlockWndXPos ;ButtonYPos = MainWindowYPos + TabSpace ;ButtonPosition = [ButtonXPos ButtonYPos ButtonWidth ButtonHeight] ; ButtonTabSpace = (NextBlockWndYPos - 2 * TabSpace - ButtonHeight * ButtonNumber) / ButtonNumber ;for num = 1: ButtonNumberTempButtonPosition = ButtonPosition ;TempButtonPosition(2) = ButtonPosition(2) + (num - 1) * (ButtonTabSpace + ButtonHeight);if findstr( ButtonStyle{num}, 'button' )TempButtonPosition(1) = TempButtonPosition(1) + 10 ;TempButtonPosition(2) = TempButtonPosition(2) + 5 ;TempButtonPosition(3) = TempButtonPosition(3) - 10 * 2 ;TempButtonPosition(4) = TempButtonPosition(4) - 5 * 2 ;elseTempButtonPosition(1) = TempButtonPosition(1) - 10 ;TempButtonPosition(2) = TempButtonPosition(2) - 5 ;TempButtonPosition(3) = TempButtonPosition(3) + 10 * 2;TempButtonPosition(4) = TempButtonPosition(4) + 5 * 2 ;endButtonHandle = uicontrol( 'Tag', ButtonTag{num}, 'Style', ButtonStyle{num}, 'Pos', TempButtonPosition,...'Foregroundcolor', FontColor{num}, 'Backgroundcolor', ButtonColor{num},...'Fontsize', 16, 'String', ButtonString{num}, 'Cal', ButtonCallback{num} ) ;if findstr( ButtonStyle{num}, 'text' )set( ButtonHandle, 'Max', 2 ) ;endif findstr( ButtonTag{num}, 'PauseButton' )set( ButtonHandle, 'Enable', 'inactive', 'ButtonDownFcn', ButtonCallback{num}, 'Cal', '' ) ; endendMainBlockAxes = axes( 'Units', 'pixels', 'Pos', MainWindowPosition, 'XTick', [], 'YTick',[], 'XTickLabel', [],...'YTickLabel', [], 'Box', 'on', 'Tag', 'MainBlockAxes', 'Hittest', 'off',...'XLim', [0 MainWindowWidth], 'YLim', [0 MainWindowHeight], 'Color', 'none' ) ;line( 'Visible', 'on', 'Tag', 'BlockHandle', 'Markersize', 18, 'Parent', MainBlockAxes, 'HitTest', 'off',...'Marker', 's', 'MarkerEdgeColor', 'k', 'XData', nan, 'YData', nan, 'LineStyle', 'none' ) ;line( 'Visible', 'off', 'Tag', 'TempBlock', 'Markersize', 18, 'Parent', MainBlockAxes, 'HitTest', 'off',...'Marker', 's', 'MarkerEdgeColor', 'k', 'XData', 130, 'YData', 30, 'LineStyle', 'none' ) ;line( 'Visible', 'off', 'Tag', 'NextBlock', 'Markersize', 18, 'Parent', NextBlockAxes, 'HitTest', 'off',...'Marker', 's', 'MarkerEdgeColor', 'k', 'XData', 30, 'YData', 30, 'LineStyle', 'none' ) ; setappdata( FigureHandle, 'XLim', [0 MainWindowWidth] )setappdata( FigureHandle, 'YLim', [0 MainWindowHeight] )handles = guihandles( FigureHandle ) ;guidata( FigureHandle, handles ) ;% -------------------------------------------------------------------------function init_FigureContent( FigureHandle )handles = guidata( FigureHandle ) ;ColorInfo = [] ;tryColorInfo = load('ColorInfo.mat') ;catchendif isempty( ColorInfo )ColorInfo.BlockColor = GetDefaultBlockColor ;ColorInfo.MainAxesColor = GetDefaultMainAxesColor ;ColorInfo.MainAxesImage.ImageData = [] ;endset( handles.MainAxes, 'Color', ColorInfo.MainAxesColor ) ;if ~isempty( ColorInfo.MainAxesImage.ImageData )ImageHandle = image( ColorInfo.MainAxesImage.ImageData, 'Parent', handles.MainAxes ) ;set( ImageHandle, ColorInfo.MainAxesImage.Property ) ;setappdata( FigureHandle, 'ImageData', ColorInfo.MainAxesImage.ImageData ) ; endset( handles.BlockHandle, 'MarkerFaceColor', ColorInfo.BlockColor ) ;set( handles.TempBlock, 'MarkerFaceColor', ColorInfo.BlockColor ) ;set( handles.NextBlock, 'MarkerFaceColor', ColorInfo.BlockColor ) ;setappdata( FigureHandle, 'BlockColor', ColorInfo.BlockColor ) ;% ------------------------------------------------------------function StartNewGame_Callback( h, StartType )handles = guidata( h ) ;global PauseTimeif nargin == 1StartType = 'NewStart' ;setappdata( handles.RussiaBlock, 'BlockNumber', 0 ) ;set( handles.BlockNumText, 'String', {'方块数','0'} ) ;setappdata( handles.RussiaBlock, 'CurrentScore', 0 ) ;set( handles.ScoreText, 'String', {'积分','0'} ) ;set( handles.BlockHandle, 'XData', nan, 'YData', nan ) ;set( handles.TempBlock, 'XData', nan, 'YData', nan ) ;TextHandle = findobj( 'Parent', handles.MainBlockAxes, 'Type', 'text' ) ; delete( TextHandle ) ;elseendset( handles.NextBlock, 'Visible', 'on' ) ;set( handles.TempBlock, 'Visible', 'on' ) ;set( handles.PauseTool, 'State', 'off' ) ;set( handles.PauseButton, 'Value', 0 ) ;YLim = get( handles.MainAxes, 'YLim' ) ;while( ishandle( h ) )TotalYData = get( handles.BlockHandle, 'YData' ) ;if any( TotalYData >= YLim(2) )% Game overtext( 20, 200, 'GameOver', 'Parent', handles.MainBlockAxes,...'FontSize', 30, 'Color', 'r', 'FontAngle', 'italic' ) ;break;endif length( TotalYData ) >= 4TotalXData = get( handles.BlockHandle, 'XData' ) ;LastBlockYData = TotalYData( end - 3: end ) ;LastBlockYData = unique( LastBlockYData ) ;CompleteLine = [] ;UsefulIndex = [] ;for num = 1: length( LastBlockYData )[YData, Index] = find( TotalYData == LastBlockYData(num) ) ;if length( YData ) == 12CompleteLine = [CompleteLine, LastBlockYData(num)] ;UsefulIndex = [UsefulIndex, Index] ;endendif ~isempty( CompleteLine )TotalXData( UsefulIndex ) = [] ;TotalYData( UsefulIndex ) = [] ;LineNumber = length( CompleteLine ) ;ScoreArray = [100 300 600 1000] ;NewScore = ScoreArray(LineNumber) ;CurrentScore = getappdata( handles.RussiaBlock, 'CurrentScore' ) ; TextString = get( handles.ScoreText, 'String' ) ;TextString{2} = CurrentScore + NewScore ;set( handles.ScoreText, 'String', TextString ) ;setappdata( handles.RussiaBlock, 'CurrentScore', CurrentScore + NewScore ) ; UpdateGameLevel( handles.RussiaBlock, CurrentScore + NewScore ) ;% 处理需要下移的方块for num = LineNumber : -1 : 1[YData, Index] = find( TotalYData > LastBlockYData(num) ) ;TotalYData(Index) = TotalYData(Index) - 20 ;endendset( handles.BlockHandle, 'XData', TotalXData, 'YData', TotalYData ) ;endBlockNumber = getappdata( handles.RussiaBlock, 'BlockNumber' ) ; TextString = get( handles.BlockNumText, 'String' ) ;TextString{2} = BlockNumber + 1 ;set( handles.BlockNumText, 'String', TextString ) ;setappdata( handles.RussiaBlock, 'BlockNumber', BlockNumber + 1 ) ; GameLevel = getappdata( handles.RussiaBlock, 'GameLevel' ) ;if isempty( GameLevel )PauseTime = 0.3 ;elsePauseTime = ceil( 20 / GameLevel ) / 100 ;endTempBlockPos.LeftStep = 0 ;TempBlockPos.DownStep = 0 ;setappdata( handles.RussiaBlock, 'TempBlockPos', TempBlockPos ) ; Status = 1;[BlockXArray,BlockYArray] = Com_GetBlock( h ) ;set( handles.TempBlock, 'XData', BlockXArray, 'YData', BlockYArray ) ; while( Status & ishandle( h ) )if(PauseTime) ~= 0pause( PauseTime )endStatus = test_MoveBlock( h, 'Down' ) ;endend% ------------------------------------------------------------------------- function KeyPress_Callback( h )handles = guidata( h ) ;PauseState = get( handles.PauseTool, 'State' ) ;if strcmp( PauseState, 'on' )returnendBoardConfig = getappdata( handles.RussiaBlock, 'BoardConfig' ) ;if isempty( BoardConfig )Left = 'leftarrow' ;Right = 'rightarrow' ;Down = 'downarrow' ;Change = 'uparrow' ;Drop = 'space' ;elseLeft = BoardConfig.Left ;Right = BoardConfig.Right ;Down = BoardConfig.Down ;Change = BoardConfig.Change ;Drop = BoardConfig.Drop ;endCurrentKey = get( handles.RussiaBlock, 'CurrentKey' ) ; switch CurrentKeycase Lefttest_MoveBlock( h, 'Left' ) ;case Righttest_MoveBlock( h, 'Right' ) ;case Downtest_MoveBlock( h, 'Down' ) ;case Changetest_MoveBlock( h, 'Change' ) ;case Droptest_MoveBlock( h, 'Drop' ) ;otherwisereturn ;end% ------------------------------------------------------------------------- function WindowColor_Callback( h )handles = guidata( h ) ;CurrentColor = get( handles.MainAxes, 'Color' ) ;NewColor = uisetcolor( CurrentColor, '请选择窗口颜色' ) ;if length( NewColor ) == 0return;elseset( handles.MainAxes, 'Color', NewColor ) ;end% ------------------------------------------------------------------------- function WindowPicture_Callback( h )handles = guidata( h ) ;[PictureFile, Path] = uigetfile( {'*.jpg; *.bmp'},'请选择图片' ); if isnumeric( PictureFile )return ;else% if length( PictureFile ) > 31% errordlg( '文件名过长,读取失败' ) ;% endtryPicture = imread( [Path, PictureFile] ) ;for num = 1: size( Picture, 3 )ValidPicture(:, :, num) = flipud( Picture(:,:,num) ) ;AxesXLim = get( handles.MainAxes, 'XLim' ) ;AxesYLim = get( handles.MainAxes, 'YLim' ) ;BlockHandle = findobj( handles.MainAxes, 'Style', 'line' ) ;cla( BlockHandle ) ;ImageXLimit = size(Picture, 2) ;ImageYLimit = size(Picture, 1) ;if diff( AxesXLim ) < size(Picture, 2) | diff( AxesYLim ) < size(Picture, 1) % 超出坐标轴范围,压缩显示XScale = diff( AxesXLim ) / size(Picture, 2) ;YScale = diff( AxesYLim ) / size(Picture, 1) ;% 取较小比例压缩Scale = min( XScale, YScale ) ;ImageXLimit = size(Picture, 2) * Scale ;ImageYLimit = size(Picture, 1) * Scale ;endImageXData(1) = AxesXLim(1) + (diff( AxesXLim ) - ImageXLimit) / 2 + 1; ImageXData(2) = ImageXData(1) + ImageXLimit - 1;ImageYData(1) = AxesYLim(1) + (diff( AxesYLim ) - ImageYLimit) / 2 + 1; ImageYData(2) = ImageYData(1) + ImageYLimit - 1;image( ValidPicture, 'Parent', handles.MainAxes, 'Hittest', 'off', ...'XData',ImageXData,'YData',ImageYData, 'Tag', 'MainImage' ); setappdata( handles.RussiaBlock, 'ImageData', ValidPicture ) ;catchErrorString = sprintf( ['读取图片失败,错误信息为:\n',lasterr] ) ; errordlg( ErrorString ) ;endend% -------------------------------------------------------------------------function BlockColor_Callback( h )handles = guidata( h ) ;CurrentColor = getappdata( handles.RussiaBlock, 'BlockColor' ) ;if isempty( CurrentColor )CurrentColor = GetDefaultBlockColor ;setappdata( handles.RussiaBlock, 'BlockColor', CurrentColor ) ;endNewColor = uisetcolor( CurrentColor, '请选择方块颜色' ) ;if length( NewColor ) == 0return;setappdata( handles.RussiaBlock, 'BlockColor', NewColor ) ; set( handles.BlockHandle, 'MarkerFaceColor', NewColor ) ;set( handles.TempBlock, 'MarkerFaceColor', NewColor ) ;set( handles.NextBlock, 'MarkerFaceColor', NewColor ) ;end% ------------------------------------------------------------------------ function Default_Callback( h )handles = guidata( h ) ;BlockColor = GetDefaultBlockColor ;AxesColor = GetDefaultMainAxesColor ;set( handles.MainAxes, 'Color', AxesColor ) ;set( handles.BlockHandle, 'MarkerFaceColor', BlockColor ) ;set( handles.TempBlock, 'MarkerFaceColor', BlockColor ) ;set( handles.NextBlock, 'MarkerFaceColor', BlockColor ) ;% ------------------------------------------------------------------------- function PauseGame_Callback( h )handles = guidata( h ) ;ToolStart = get( handles.PauseTool, 'State' ) ;if strcmp( ToolStart, 'on' )set( handles.PauseButton, 'Value', 1 ) ;waitfor( handles.PauseTool, 'State', 'off' ) ;elseset( handles.PauseButton, 'Value', 0 ) ;end% ------------------------------------------------------------------------- function ButtonPauseGame_Callback( h )handles = guidata( h ) ;ToggleButtonValue = get( h, 'Value' ) ;if ToggleButtonValue == 0set( h, 'Value', 1 ) ;set( h, 'String', '继续' ) ;set( handles.PauseTool, 'State', 'on' ) ;waitfor( handles.PauseTool, 'State', 'off' ) ;elseset( h, 'Value', 0 ) ;set( h, 'String', '暂停' ) ;set( handles.PauseTool, 'State', 'off' ) ;set( handles.RussiaBlock, 'CurrentObject', handles.MainAxes ) ; end% ------------------------------------------------------------------------function CloseFigure_Callback( h )handles = guidata( h ) ;BlockColor = getappdata( handles.RussiaBlock, 'BlockColor' ) ; MainAxesColor = get( handles.MainAxes, 'Color' ) ; MainAxesImageHandle = findobj( handles.MainAxes, 'Type', 'image' ) ;if ~isempty( MainAxesImageHandle )MainAxesImage.Property.Tag = get( MainAxesImageHandle, 'Tag' ); MainAxesImage.Property.Hittest = get( MainAxesImageHandle, 'Hittest' ); MainAxesImage.Property.XData = get( MainAxesImageHandle, 'XData' ); MainAxesImage.Property.YData = get( MainAxesImageHandle, 'YData' ); MainAxesImage.ImageData = getappdata( handles.RussiaBlock, 'ImageData' ) ; elseMainAxesImage.ImageData = [] ;endsave ColorInfo.mat BlockColor MainAxesColor MainAxesImagedelete( handles.RussiaBlock ) ;% -------------------------------------------------------------------------function Color = GetDefaultBlockColorColor = [0 0 1] ;% -------------------------------------------------------------------------function Color = GetDefaultMainAxesColorColor = [1 1 1] ;% ----------------------------------------------------------------function [BlockXArray, BlockYArray] = Com_GetBlock( varargin )global BlockIndex ;BlockXArray = [] ;BlockYArray = [] ;handles = guidata( varargin{1} ) ;if nargin == 1BlockArray = getappdata( handles.RussiaBlock, 'BlockArray' ) ;BlockIndex = ceil( rand(1) * 24 ) ;else % nargin == 2BlockIndex = varargin{2} ;endswitch(BlockIndex)case {1,2,3,4} % 方块BlockXArray = [0;0;1;1] * 20 - 10 ;BlockYArray = [0;1;1;0] * 20 - 10 ;case {5,6} % 竖长条BlockXArray = [0;0;0;0] * 20 - 10 ;case {7,8} % 横长条BlockXArray = [-1;0;1;2] * 20 - 10 ; BlockYArray = [1;1;1;1] * 20 - 10 ; case {9} % 4类T T1 BlockXArray = [-1;0;1;0] * 20 - 10 ; BlockYArray = [1;1;1;0] * 20 - 10 ; case {10} % T2BlockXArray = [0;0;1;0] * 20 - 10 ; BlockYArray = [2;1;1;0] * 20 - 10 ; case {11} % T3BlockXArray = [0;0;1;-1] * 20 - 10 ; BlockYArray = [2;1;1;1] * 20 - 10 ; case {12} % T4BlockXArray = [0;0;0;-1] * 20 - 10 ; BlockYArray = [2;1;0;1] * 20 - 10 ; case {13} % 8类L L1 BlockXArray = [0;0;0;1] * 20 - 10 ; BlockYArray = [1;0;-1;-1] * 20 - 10 ; case {14} % L2BlockXArray = [-1;0;1;1] * 20 - 10 ; BlockYArray = [0;0;0;1] * 20 - 10 ; case {15} % L3BlockXArray = [-1;0;0;0] * 20 - 10 ; BlockYArray = [1;1;0;-1] * 20 - 10 ; case {16} % L4BlockXArray = [-1;-1;0;1] * 20 - 10 ; BlockYArray = [-1;0;0;0] * 20 - 10 ; case {17} % L5BlockXArray = [-1;0;0;0] * 20 - 10 ; BlockYArray = [-1;-1;0;1] * 20 - 10 ; case {18} % L6BlockXArray = [-1;-1;0;1] * 20 - 10 ; BlockYArray = [1;0;0;0] * 20 - 10 ; case {19} % L7BlockXArray = [0;0;0;1] * 20 - 10 ; BlockYArray = [-1;0;1;1] * 20 - 10 ; case {20} % L8BlockXArray = [-1;0;1;1] * 20 - 10 ; BlockYArray = [0;0;0;-1] * 20 - 10 ; case {21 22} % 4类Z Z1 BlockXArray = [-1;0;0;1] * 20 - 10 ; BlockYArray = [1;1;0;0] * 20 - 10 ; case {23 24} % Z2BlockYArray = [-1;0;0;1] * 20 - 10 ;case {25 26} % Z3BlockXArray = [-1;0;0;1] * 20 - 10 ;BlockYArray = [0;0;1;1] * 20 - 10 ;case {27 28} % Z4BlockXArray = [0;0;1;1] * 20 - 10 ;BlockYArray = [1;0;0;-1] * 20 - 10 ;endif nargin == 1NewBlockArray.BlockXArray = BlockXArray ;NewBlockArray.BlockYArray = BlockYArray ;NewBlockArray.BlockIndex = BlockIndex ;NextAxesXLim = get( handles.NextBlockAxes, 'XLim' ) ;NextAxesYLim = get( handles.NextBlockAxes, 'YLim' ) ;set( handles.NextBlock, 'XData', [BlockXArray + 0.5 * diff( NextAxesXLim ) -ceil( sum( BlockXArray ) / 4 ) ],...'YData', [BlockYArray + 0.5 * diff( NextAxesYLim )] - ceil( sum( BlockYArray ) / 4 ) ) ; setappdata( handles.RussiaBlock, 'BlockArray', NewBlockArray ) ;if isempty( BlockArray )Com_GetBlock( varargin{1} ) ;elseBlockXArray = BlockArray.BlockXArray ;BlockYArray = BlockArray.BlockYArray ;BlockIndex = BlockArray.BlockIndex ;endendAxesXLim = getappdata( handles.RussiaBlock, 'XLim' ) ;AxesYLim = getappdata( handles.RussiaBlock, 'YLim' ) ;BlockXArray = BlockXArray + 0.5 * diff( AxesXLim ) ;BlockYArray = BlockYArray + diff( AxesYLim ) ;% -------------------------------------------------------------------------function Status = test_MoveBlock( h, MoveMode )Status = 1;if ~ishandle( h )returnendhandles = guidata( h ) ;TempXData = get( handles.TempBlock, 'XData' ) ;TempYData = get( handles.TempBlock, 'YData' ) ;TempXData = TempXData';TempYData = TempYData' ;TotalXData = get( handles.BlockHandle, 'XData' ) ;TotalYData = get( handles.BlockHandle, 'YData' ) ;TotalXData = TotalXData' ;TotalYData = TotalYData' ;TempBlockPos = getappdata( handles.RussiaBlock, 'TempBlockPos' ) ;if isempty( TempBlockPos )returnendAxesXLim = getappdata( handles.RussiaBlock, 'XLim' ) ;AxesYLim = getappdata( handles.RussiaBlock, 'YLim' ) ;switch MoveModecase 'Left'if any( TempXData - 20 < AxesXLim(1) )returnendTestArray = ismember( [TempXData - 20, TempYData], [TotalXData, TotalYData], 'rows' ) ;if any( TestArray )return;elseset( handles.TempBlock, 'XData', TempXData - 20 ) ;TempBlockPos.LeftStep = TempBlockPos.LeftStep + 1 ;setappdata( handles.RussiaBlock, 'TempBlockPos', TempBlockPos ) ;endcase 'Right'if any( TempXData + 20 > AxesXLim(2) )returnendTestArray = ismember( [TempXData + 20, TempYData], [TotalXData, TotalYData], 'rows' ) ;if any( TestArray )return;elseset( handles.TempBlock, 'XData', TempXData + 20 ) ;TempBlockPos.LeftStep = TempBlockPos.LeftStep - 1 ;setappdata( handles.RussiaBlock, 'TempBlockPos', TempBlockPos ) ;endcase 'Down'if any( TempYData - 20 < AxesYLim(1) )set( handles.BlockHandle, 'XData', [TotalXData; TempXData],...'YData', [TotalYData; TempYData] ) ;Status = 0 ;returnendTestArray = ismember( [TempXData, TempYData - 20], [TotalXData, TotalYData], 'rows' ) ;if any( TestArray )set( handles.BlockHandle, 'XData', [TotalXData; TempXData],...'YData', [TotalYData; TempYData] ) ;Status = 0 ;elseset( handles.TempBlock, 'YData', TempYData - 20 ) ;TempBlockPos.DownStep = TempBlockPos.DownStep + 1 ;setappdata( handles.RussiaBlock, 'TempBlockPos', TempBlockPos ) ;endcase 'Drop'global PauseTimePauseTime = 0 ;case 'Change'global BlockIndexOldBlockIndex = BlockIndex ;switch BlockIndexcase {1,2,3,4}return;case {5,6}NewIndex = 7 ;case {7,8}NewIndex = 5 ;case {9,10,11,12}NewIndex = mod( OldBlockIndex, 4 ) + 9;case {13,14,15,16}NewIndex = mod( OldBlockIndex, 4 ) + 13;case {17,18,19,20}NewIndex = mod( OldBlockIndex, 4 ) + 17;case {21,22}NewIndex = 23;case {23,24}NewIndex = 21;case {25,26}NewIndex = 27 ;case {27,28}NewIndex = 25 ;end[BlockXArray, BlockYArray] = Com_GetBlock( h, NewIndex ) ;NewTempXData = BlockXArray - TempBlockPos.LeftStep * 20 ; NewTempYData = BlockYArray - TempBlockPos.DownStep * 20 ;if any( NewTempXData < AxesXLim(1) ) | any( NewTempXData > AxesXLim(2) ) |...。

基于MATLAB的2048小游戏

基于MATLAB的2048小游戏

基于MATLAB的2048小游戏第一章:实验目的以及玩法演示引言2048是一款广受欢迎的滑动拼图游戏。

玩家需要通过滑动屏幕来移动方块,当两个相同数字的方块碰撞时,它们会合并成一个更大的数字。

游戏的目标是创建一个具有数字2048的方块,但如果在移动过程中无法进行任何有效的移动,则游戏结束。

在本次课程设计中,我们将使用MATLAB语言来设计并实现一个简化版的2048游戏。

MATLAB是一种高效的编程语言,适用于算法开发、数据可视化以及数据分析等。

1.1实验目的:1、运用MATLAB设计2048小游戏。

2、提升MATLAB代码编写能力。

3、学会利用MATLAB GUI设计图形交互界面。

1.2演示:2048游戏规则:(1)点击键盘上的上下左右按钮,控制数字的滑动;(2)滑动的数字如果碰到相同数字,则合并为更高级数字;(3)有数字合并后,会在随机位置新增加一个随机的数字2或4;(4)游戏结束:游戏界面被数字填满不能再滑动;(5)游戏总分数:游戏过程中的数字相加总和。

第二章:设计思路以及流程2.1设计思路错误!未找到引用源。

:首先构成一个4成4的矩阵,在表格中生成最初的数字2,生成位置随机。

其次设计四个按键分别实现上下左右移动整个矩形里的数字,随后合并相同的数字,当矩阵中数字满了且无法继续合并时游戏结束。

最后设计出得分面板,用来记录游戏补数转化成得分。

2.2功能需求描述l、图形用户界面:2048的最大特点就是玩家对图形界面里的数字进行操作,也就是是玩家与游戏的互动2、当前分数scoRE与最高分数的显示:在我们设计的2048游戏中当前分数取了页面i内所有数字相加的值为分数,对玩家玩游戏的进展有直接性、客观性的展现,同时,最高分数取了以往玩家退出游戏时所保存分数的最高分3、数字颜色‘游戏中数宇的颜色以2为首项的等比数列变化,即2、4、8、l6、32、“、128、256、5l2、I024、2048_.对应的数字卡片变色4、游戏的退出:游戏退出时,我们采用弹出对话框的确认玩家是否真的要退出游戏,当然这样做更符合游戏人性化设计的观念。

matlab编写的迷宫小游戏

matlab编写的迷宫小游戏

function mazerow = 20;col = 39;rand('state',sum(100*clock))[cc,rr] = meshgrid(1:col,1:row);state = reshape([1:row*col],row,col);id = reshape([1:row*col],row,col);ptr_left = zeros(size(id));ptr_up = zeros(size(id));ptr_right = zeros(size(id));ptr_down = zeros(size(id));ptr_left(:,2:size(id,2)) = id(:,1:size(id,2)-1);ptr_up(2:size(id,1),:) = id(1:size(id,1)-1,:);ptr_right(:,1:size(id,2)-1) = id(:,2:size(id,2));ptr_down(1:size(id,1)-1,:) = id(2:size(id,1),:);the_maze = cat(2,reshape(id,row*col,1),reshape(rr,row*col,1),reshape(cc,row*col,1),reshape(state, row*col,1),...reshape(ptr_left,row*col,1),reshape(ptr_up,row*col,1),reshape(ptr_right,row*col,1),res hape(ptr_down,row*col,1) );the_maze = sortrows(the_maze);id = the_maze(:,1);rr = the_maze(:,2);cc = the_maze(:,3);state = the_maze(:,4);ptr_left = the_maze(:,5);ptr_up = the_maze(:,6);ptr_right = the_maze(:,7);ptr_down = the_maze(:,8);clear the_maze;[state, ptr_left, ptr_up, ptr_right, ptr_down]=...make_pattern(row,col,rr, cc, state, ptr_left, ptr_up, ptr_right, ptr_down);f = figure('Name','迷宫',... %显示图形窗口的标题'Numbertitle','off',... %标题栏中是否显示’Figure No. n’,其中n为图形窗口的编号'Menubar','none',... %转换图形窗口菜单条的“关”'Color','white',...'DoubleBuffer','on',...'outerposition',get(0,'ScreenSize'),...'Colormap',[.1 .71 0;.3 .4 .4;0 0 0;1 1 0],...'CloseRequestFcn',@close_window,...'KeyPressFcn',@move_spot);%建菜单gameMenu = uimenu(f,'Label','游戏');uimenu(gameMenu,'Label','新游戏','Accelerator','N','Callback',@new_game);uimenu(gameMenu,'Label','退出','Accelerator','Q','Separator','on','Callback',@close_window);show_maze(row, col, rr, cc, ptr_left, ptr_up, ptr_right, ptr_down,f);% 开始cursor_pos = [1,1];current_id = 1;text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color' ,'r');%计时timing = 1;start_time = clock;%按下键盘时触发function move_spot(src,evnt)%获取方向建% 记录过程key = double(get(gcbf,'Currentcharacter'));if ~(ischar(key)||isscalar(key))return;endif ~all(cursor_pos == [col,row])key = double(get(gcbf,'Currentcharacter'));switch keycase 28 % leftif ptr_left(current_id) < 0 % check for legal movecurrent_id =- ptr_left(current_id);text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color' ,[.8,.8,.8]);cursor_pos(1) = cursor_pos(1) - 1;text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color' ,'r');endcase 29 % rightif ptr_right(current_id) < 0 % check for legal movecurrent_id =- ptr_right(current_id);text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color' ,[.8,.8,.8]);cursor_pos(1) = cursor_pos(1) + 1;text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color' ,'r');endcase 30 % upif ptr_up(current_id) < 0 % check for legal movecurrent_id =- ptr_up(current_id);text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color' ,[.8,.8,.8]);cursor_pos(2) = cursor_pos(2) - 1;text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color' ,'r');endcase 31 % downif ptr_down(current_id) < 0 % check for legal movecurrent_id =- ptr_down(current_id);text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color' ,[.8,.8,.8]);cursor_pos(2) = cursor_pos(2) + 1;text(cursor_pos(1),cursor_pos(2),'\diamondsuit','HorizontalAlignment','Center','color' ,'r');endotherwiseendendif all(cursor_pos == [col,row]) && timingtitle(cat(2,' Winning Time ',num2str(round(etime(clock,start_time)*100)/100),'(sec)'),'FontSize',20)timing = 0;endend%选择新游戏时触发function new_game(src,evnt)if ~all(cursor_pos == [col,row])choice = questdlg('游戏还未结束,你确定要重新开始吗?','迷宫','确定','取消','取消');if strcmp(choice,'确定')closereq;maze;endelseclosereq;maze;endend%关闭窗口时触发function close_window(src,evnt)if ~all(cursor_pos == [col,row])choice = questdlg('游戏还未结束,你确定要退出吗?','迷宫','确定','取消','取消');if strcmp(choice,'确定')closereq;endelseclosereq;endendend%显示迷宫function show_maze(row, col, rr, cc, ptr_left, ptr_up, ptr_right, ptr_down,h)figure(h)line([.5,col+.5],[.5,.5]) % draw top borderline([.5,col+.5],[row+.5,row+.5]) % draw bottom borderline([.5,.5],[1.5,row+.5]) % draw left borderline([col+.5,col+.5],[.5,row-.5]) % draw right borderfor ii=1:length(ptr_right)if ptr_right(ii)>0 % right passage blockedline([cc(ii)+.5,cc(ii)+.5],[rr(ii)-.5,rr(ii)+.5]);hold onendif ptr_down(ii)>0 % down passage blockedline([cc(ii)-.5,cc(ii)+.5],[rr(ii)+.5,rr(ii)+.5]);hold onendendaxis equalaxis([.5,col+.5,.5,row+.5])axis offset(gca,'YDir','reverse')end%产生边界道路信息function [state, ptr_left, ptr_up, ptr_right, ptr_down]=make_pattern(row,col, rr, cc, state, ptr_left, ptr_up, ptr_right, ptr_down)while max(state) > 1tid = ceil(col*row*rand(15,1));cityblock = cc(tid) + rr(tid);is_linked = (state(tid) == 1);temp = sortrows(cat(2,tid,cityblock,is_linked),[3,2]);tid = temp(1,1);dir = ceil(4*rand);switch dircase 1if ptr_left(tid) > 0 && state(tid) ~= state(ptr_left(tid))state( state == state(tid) | state == state(ptr_left(tid)) ) = min([state(tid),state(ptr_left(tid))]);ptr_right(ptr_left(tid)) =- ptr_right(ptr_left(tid));ptr_left(tid) =- ptr_left(tid);endcase 2if ptr_right(tid) > 0 && state(tid) ~= state(ptr_right(tid))state( state == state(tid) | state == state(ptr_right(tid)) ) = min([state(tid),state(ptr_right(tid))]);ptr_left(ptr_right(tid)) =- ptr_left(ptr_right(tid));ptr_right(tid) =- ptr_right(tid);endcase 3if ptr_up(tid) > 0 && state(tid) ~= state(ptr_up(tid))state( state == state(tid) | state == state(ptr_up(tid)) ) = min([state(tid),state(ptr_up(tid))]);ptr_down(ptr_up(tid)) =- ptr_down(ptr_up(tid));ptr_up(tid) =- ptr_up(tid);endcase 4if ptr_down(tid) > 0 && state(tid) ~= state(ptr_down(tid))state( state == state(tid) | state == state(ptr_down(tid)) ) = min([state(tid),state(ptr_down(tid))]);ptr_up(ptr_down(tid)) =- ptr_up(ptr_down(tid));ptr_down(tid) =- ptr_down(tid);endotherwiseerror('quit')endendend-----精心整理,希望对您有所帮助!。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

MATLAB游戏程序目录1.空格游戏 (2)2.华容道 (3)3.凑五子棋 (14)4.2048 (19)5.俄罗斯方块 (24)1.空格游戏function pintu1()A = gen();G = [1 2 3;4 5 6;7 8 0];drawmap(A);while 1[xpos,ypos] = ginput(1);col = ceil(xpos);row = 3-ceil(ypos)+1;num = A(row,col);if row>1&A(row-1,col)==0A(row-1,col) = num;A(row,col) = 0;endif row<3&A(row+1,col)==0A(row+1,col) = num;A(row,col) = 0;endif col>1&A(row,col-1)==0A(row,col-1) = num;A(row,col) = 0;endif col<3&A(row,col+1)==0A(row,col+1) = num;A(row,col) = 0;enddrawmap(A)zt = abs(A-G);if sum(zt(:))==0msgbox('恭喜您成功完成!')breakendendfunction drawmap(A)clf;hold online([0 3],[0 0],'linewidth',4);line([3 3],[0 3],'linewidth',4);line([0 3],[3 3],'linewidth',4);line([0 0],[0 3],'linewidth',4);for i = 1:3for j = 1:3drawrect([j-1 3-i],[j 3-i],[j 3-i+1],[j-1 3-i+1],'y',A(i,j));endendaxis equalaxis offfunction drawrect(x1,x2,x3,x4,color,num)x = [x1(1) x2(1) x3(1) x4(1)];y = [x1(2) x2(2) x3(2) x4(2)];fill(x,y,color)if num==0text(0.5*(x1(1)+x2(1)),0.5*(x1(2)+x4(2)),' ','fontsize',24)elsetext(0.5*(x1(1)+x2(1))-0.05,0.5*(x1(2)+x4(2)),num2str(num),'fontsize',24) endfunction y = gen()y = inf*ones(1,9);for i = 1:9while 1a = randint(1,1,9);if isempty(find(y==a))y(i) = a;breakendendendy = reshape(y,3,3);2.华容道function huarongdao()A = [2 1 1 3;2 1 1 3;4 6 6 5;4 7 7 5;7 0 0 7];drawmap(A)while 1if A(5,2)==1&A(5,3)==1ch = menu('曹操成功逃出华容道!如果要继续玩,按“是”,否则按“否”','是','否');switch chcase 1huarongdao();case 2returnendend[xpos,ypos] = ginput(1);col = ceil(xpos);row = 5-ceil(ypos)+1;juese = A(row,col);switch juesecase 1%点击了曹操[I,J] = find(A==1);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0])A([rn,rm],ln-1)=[1;1];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0])A([rn,rm],lm+1)=[1;1];A([rn,rm],ln)=[0;0];drawmap(A)end%判断是否能向下移if rn>1&isequalm(A(rn-1,[ln,lm]),[0,0])A(rn-1,[ln,lm])=[1,1];A(rn+1,[ln,lm])=[0,0];drawmap(A)end%判断是否能向上移if rm<5&isequalm(A(rm+1,[ln,lm]),[0,0])A(rm+1,[ln,lm])=[1,1];A(rm-1,[ln,lm])=[0,0];drawmap(A)endcase 2% 点击了黄忠[I,J] = find(A==2);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0])A([rn,rm],ln-1)=[2;2];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0])A([rn,rm],lm+1)=[2;2];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 2;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm+1,ln) = 2;A(rm-1,ln) = 0;drawmap(A)endelse%只能上移A(rn-1,ln) = 2;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 2;A(rm-1,ln) = 0;drawmap(A)endcase 3%张飞[I,J] = find(A==3);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0])A([rn,rm],ln-1)=[3;3];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0])A([rn,rm],lm+1)=[3;3];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 3;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm+1,ln) = 3;A(rm-1,ln) = 0;endelse%只能上移A(rn-1,ln) = 3;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 3;A(rm-1,ln) = 0;drawmap(A)endcase 4%马超[I,J] = find(A==4);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0])A([rn,rm],ln-1)=[4;4];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0])A([rn,rm],lm+1)=[4;4];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 4;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm+1,ln) = 4;drawmap(A)endelse%只能上移A(rn-1,ln) = 4;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 4;A(rm-1,ln) = 0;drawmap(A)endcase 5%赵云[I,J] = find(A==5);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0])A([rn,rm],ln-1)=[5;5];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0])A([rn,rm],lm+1)=[5;5];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 5;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm-1,ln) = 0;drawmap(A)endelse%只能上移A(rn-1,ln) = 5;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 5;A(rm-1,ln) = 0;drawmap(A)endcase 6%关羽[I,J] = find(A==6);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向上移if rn>1 & isequalm(A(rn-1,[ln,lm]),[0,0])A(rn-1,[ln,lm])=[6,6];A(rn,[ln,lm])=[0,0];drawmap(A)end%判断是否能向下移if rm<5&isequalm(A(rm+1,[ln,lm]),[0,0])A(rm+1,[ln,lm])=[6,6];A(rm,[ln,lm])=[0,0];drawmap(A)endif ln>1&A(rn,ln-1)==0if lm<4&A(rm,lm+1)==0%如果又能左移又能右移,则要点击的部位ch = menu('请选择移到的方向:','左','右')switch chcase 1%左移A(rm,ln-1) = 6;A(rm,ln+1) = 0;drawmap(A)case 2%右移A(rm,lm+1) = 6;A(rm,lm-1) = 0;drawmap(A)endelse%只能左移A(rm,ln-1) = 6;A(rm,ln+1) = 0;drawmap(A)endelseif lm<4&A(rm,lm+1)==0A(rm,lm+1) = 6;A(rm,lm-1) = 0;drawmap(A)endcase 7 %小卒if row>1&A(row-1,col)==0 % 上if col>1&A(row,col-1)==0 % 左ch = menu('请选择移到的方向:','上','左')switch chcase 1A(row-1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col-1) = 7;A(row,col) = 0;drawmap(A)endelseif row<5&A(row+1,col)==0% 下ch = menu('请选择移到的方向:','上','下')switch chcase 1A(row-1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row+1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col<4&A(row,col+1)==0 %右ch = menu('请选择移到的方向:','上','右')switch chcase 1A(row-1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endelse %只能向上A(row-1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col>1&A(row,col-1)==0%左if row<5&A(row+1,col)==0%下ch = menu('请选择移到的方向:','左','下')switch chcase 1A(row,col-1) = 7;A(row,col) = 0;drawmap(A)case 2A(row+1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col<4&A(row,col+1)==0%右ch = menu('请选择移到的方向:','左','右')switch chcase 1A(row,col-1) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endelse%只能向左A(row,col-1) = 7;A(row,col) = 0;drawmap(A)endelseif row<5&A(row+1,col)==0%下if col<4&A(row,col+1)==0%右ch = menu('请选择移到的方向:','下','右')switch chcase 1A(row+1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endelse%只能向下A(row+1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col<4&A(row,col+1)==0%只能向右A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endendendfunction drawmap(A)clfhold on%曹操[I J] = find(A==1);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'r')text(0.5*(x1+x2)-0.5,0.5*(y1+y2),'曹操','fontsize',28)% 黄忠[I,J] = find(A==2);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'黄','fontsize',28) text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'忠','fontsize',28)% 张飞[I,J] = find(A==3);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'张','fontsize',28) text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'飞','fontsize',28)% 马超[I,J] = find(A==4);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'马','fontsize',28) text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'超','fontsize',28)% 赵云[I,J] = find(A==5);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'赵','fontsize',28) text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'云','fontsize',28)% 关羽[I,J] = find(A==6);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+0.5*(x1+x2))-0.26,0.5*(y1+y2),'关','fontsize',28) text(0.5*(0.5*(x1+x2)+x2)-0.26,0.5*(y1+y2),'羽','fontsize',28)%小卒[I,J] = find(A==7);for i = 1:length(I)x1 = J(i)-1;x2 = J(i);y1 = 5-(I(i)-1);y2 = 5-I(i);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'g')text(0.5*(x1+x2)-0.26,0.5*(y1+y2),'卒','fontsize',28)end% 画背景line([0 4],[0 0],'color','b','linewidth',4)line([0 4],[5 5],'color','b','linewidth',4)line([0 0],[0 5],'color','b','linewidth',4)line([4 4],[0 5],'color','b','linewidth',4)for i = 1:4line([0 4],[i i],'color','b','linestyle','--')endfor i = 1:3line([i i],[0 5],'color','b','linestyle','--')endaxis equalaxis([0 4 0 5])axis offfunction drawrect(x1,x2,x3,x4,color)x = [x1(1) x2(1) x3(1) x4(1)];y = [x1(2) x2(2) x3(2) x4(2)];fill(x,y,color)3.凑五子棋function [ ] = five()global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha sshf=figure('resize','off','name','five',...'position',[360 280 560 420],'numbertitle','off');set(gcf,'menubar','none','color',[0.3 0.3 0.3])set(gca,'position',[0.2300 0.1100 0.7750 0.8150]) set(gca,'xlim',[0,9],'ylim',[0,9])set(ha,'xtick',[],'ytick',[],'box','on')set(ha,'color',[0.7 0.6,0.6])set(ha,'DataAspectRatio',[1 1 1],'PlotBoxAspectRatio',[1 1 1])x=repmat([0;9],1,9);y=[1:9;1:9];line(x,y,'color','k')line(y,x,'color','k')hst=uicontrol('style','text','string','Score','fontsize',30,...'units','normal','position',[0.02,0.55,0.26,0.14],'parent',hf,...'ForegroundColor','w','backgroundcolor',[0.3 0.3 0.3],...'fontweight','bold');hsc=uicontrol('style','text','string','0','fontsize',24,...'units','normal','position',[0.02,0.4,0.26,0.14],'parent',hf,...'ForegroundColor','w','backgroundcolor',[0.3 0.3 0.3],...'fontweight','bold');hbt=uicontrol('style','pushbutton','string','Restart','fontsize',18,...'units','normal','position',[0.02,0.16,0.26,0.14],'parent',hf,...'fontweight','bold','callback',@restart);color=[...1 1 0;1 0 1;0 1 1;1 0 0;0 1 0;0 0 1;0.7 0.3 0;];h1=annotation('ellipse',[0.04,0.84,0.06,0.08],'facecolor','k');h2=annotation('ellipse',[0.12,0.84,0.06,0.08],'facecolor','k');h3=annotation('ellipse',[0.2,0.84,0.06,0.08],'facecolor','k');set(ha,'buttondownfcn',@select2)initializefunction initialize()global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ssa=zeros(9);h=zeros(9)*NaN;m1=[];n1=[];m2=[];n2=[];ss=0;k=rs(1:81,5);t=ceil(rand(1,5)*7);a(k)=t;[m,n] = ind2sub([9,9],k);y=9.5-m;x=n-0.5;for p=1:5h(k(p))=line(x(p),y(p),'marker','o','markersize',24,...'markerfacecolor',color(t(p),:),'markeredgecolor','none',...'buttondownfcn',@select1);endt=ceil(rand(1,3)*7);set(h1,'facecolor',color(t(1),:))set(h2,'facecolor',color(t(2),:))set(h3,'facecolor',color(t(3),:))function [k]=rs(s,n);for m=1:nt=ceil(rand*length(s));k(m)=s(t);s(t)=[];endfunction select1(src,eventdata)global a h m1 n1n1=ceil(get(src,'xdata'));m1=ceil(9-get(src,'ydata'));set(h(~isnan(h)),'markeredgecolor','none')set(src,'markeredgecolor','w')function select2(src,eventdata)global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ssif isempty(m1) || isempty(n1)returnendcp=get(src,'currentpoint');n2=ceil(cp(1,1));m2=ceil(9-cp(1,2));if a(m2,n2)returnendb=~a;b(m1,n1)=1;b=bwlabel(b,4);if b(m1,n1)~=b(m2,n2)enda(m2,n2)=a(m1,n1);a(m1,n1)=0;h(m2,n2)=h(m1,n1);h(m1,n1)=NaN;set(h(m2,n2),'xdata',n2-0.5,'ydata',9.5-m2,'markeredgecolor','none') m1=[];n1=[];judgement;if sum(sum(~a))<3hgo=text(1,4.5,'Game Over','fontsize',36,'fontweight',...'bold','parent',src);pause(3)delete(hgo);delete(h(~isnan(h)))set(hsc,'string','0')initialize;returnendif ~ssnew;endfunction judgementglobal a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ssb=logical(zeros(9,9));ss=0;left=0;right=0;up=0;down=0;lu=0;rd=0;ld=0;ru=0;while n2-left-1>0 && a(m2,n2-left-1)==a(m2,n2)left=left+1;endwhile n2+right+1<10 && a(m2,n2+right+1)==a(m2,n2)right=right+1;endwhile m2-up-1>0 && a(m2-up-1,n2)==a(m2,n2)up=up+1;endwhile m2+down+1<10 && a(m2+down+1,n2)==a(m2,n2)down=down+1;endwhile n2-lu-1>0 && m2-lu-1>0 && a(m2-lu-1,n2-lu-1)==a(m2,n2) lu=lu+1;endwhile n2+rd+1<10 && m2+rd+1<10 && a(m2+rd+1,n2+rd+1)==a(m2,n2) rd=rd+1;endwhile n2-ld-1>0 && m2+ld+1<10 && a(m2+ld+1,n2-ld-1)==a(m2,n2) ld=ld+1;endwhile n2+ru+1<10 && m2-ru-1>0 && a(m2-ru-1,n2+ru+1)==a(m2,n2) ru=ru+1;endif left+right+1>=5b(m2,n2-left:n2+right)=1;endif up+down+1>=5b(m2-up:m2+down,n2)=1;endif lu+rd+1>=5ind=sub2ind([9,9],m2-lu:m2+rd,n2-lu:n2+rd);b(ind)=1;endif ld+ru+1>=5ind=sub2ind([9,9],m2+ld:-1:m2-ru,n2-ld:n2+ru);b(ind)=1;endif sum(sum(b))a(b)=0;delete(h(b));h(b)=NaN;score=score+sum(sum(b));set(hsc,'string',num2str(score))ss=1;endfunction newglobal a h m1 n1 m2 n2 t h1 h2 h3 color score hsc hak=rs(find(~a),3);a(k)=t;[mt,nt] = ind2sub([9,9],k);y=9.5-mt;x=nt-0.5;for p=1:3h(k(p))=line(x(p),y(p),'marker','o','markersize',24,...'markerfacecolor',color(t(p),:),'markeredgecolor','none',...'buttondownfcn',@select1);endfor p=1:3m2=mt(p);n2=nt(p);judgement;endif sum(sum(~a))==0hgo=text(1,4.5,'Game Over','fontsize',36,'fontweight',...'bold','parent',ha);pause(3)delete(hgo);delete(h(~isnan(h)))set(hsc,'string','0')initialize;returnendt=ceil(rand(1,3)*7);set(h1,'facecolor',color(t(1),:))set(h2,'facecolor',color(t(2),:))set(h3,'facecolor',color(t(3),:))function restart(src,eventdata)global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ssdelete(h(~isnan(h)))set(hsc,'string','0')initialize;4.2048function g2048(action)global totalscore flag score_boardif nargin<1figure_h=figure;set(figure_h,'Units','points')set(figure_h,'UserData',figure_h);totalscore=0;flag=0;score_board=zeros(1,16);action='initialize';endswitch actioncase 'initialize';figure_h=get(gcf,'UserData');set(figure_h,...'Color',[0.4 0.4 0.4],...'Menubar','none',...'Name','2048',...'NumberTitle','off',...'Position',[200 200 320 355],...'Resize','off');axis('off')game_score=uicontrol(figure_h,... 'BackgroundColor',[1 1 1],...'ForegroundColor',[0 0 0], ...'HorizontalAlignment','center',... 'FontSize',12,...'Units','points',...'Position',[235 305 65 30],...'String','Score',...'Style','edit',...'Tag','game_score');new_game_h=uicontrol(figure_h,... 'Callback','g2048 restart',...'FontSize',12, ...'Units','points',...'Position',[35 30 65 30],...'String','New Game',...'Style','pushbutton');% closeclose_h=uicontrol(figure_h,...'Callback','close(gcf)',...'Fontsize',12, ...'Units','points',...'Position',[225 30 65 30],...'String','Close',...'Style','pushbutton');% rightmove_right=uicontrol(figure_h,... 'Callback','g2048 right',...'Fontsize',12, ...'Units','points',...'Position',[255 185 60 30],...'String','Right',...'Style','pushbutton');% leftmove_left=uicontrol(figure_h,...'Callback','g2048 left',...'Fontsize',12, ...'Units','points',...'Position',[5 185 60 30],...'String','Left',...'Style','pushbutton');% upmove_up=uicontrol(figure_h,...'Callback','g2048 up',...'Fontsize',12, ...'Units','points',...'Position',[130 300 60 30],...'String','Up',...'Style','pushbutton');% downmove_down=uicontrol(figure_h,...'Callback','g2048 down',...'Fontsize',12, ...'Units','points',...'Position',[130 80 60 30],...'String','Down',...'Style','pushbutton');% setup the game boardirows=1;for counter=1:16jcols=rem(counter,4);if jcols==0jcols=4;endposition=[40*jcols+40 85+40*irows 40 40]; index=(irows-1)*4+jcols;if jcols==4irows=irows+1;endboard.squares(index)=uicontrol(figure_h,... 'FontSize',18,...'FontWeight','bold',...'Units','points',...'Position',position,...'Style','pushbutton',...'Tag',num2str(index));endset(figure_h,'userdata',board);g2048('restart')case 'restart'totalscore=0;score_board=zeros(1,16);g2048('addnum') ;g2048('addnum') ;g2048('show')case'show'num_0=find(score_board==0);board=get(gcf,'UserData');set(board.squares,{'string'},num2cell(score_board)')set(board.squares,...'BackgroundColor',[0.701961 0.701961 0.701961],...'Enable','on',...'Visible','on')set(board.squares(num_0),...'BackgroundColor','black',...'Enable','off',...'String',' ');score_handle=findobj(gcf,'Tag','game_score');set(score_handle,...'String',num2str(totalscore),...'Tag','game_score');case 'down'C=score_board;for i=1:4A=[score_board(i) score_board(i+4) score_board(i+8) score_board(i+12)];[B score]=move(A);score_board(i)=B(1); score_board(i+4)=B(2);score_board(i+8)=B(3); score_board(i+12)=B(4); totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase 'up'C=score_board;for i=13:16A=[score_board(i) score_board(i-4) score_board(i-8) score_board(i-12)];[B score]=move(A);score_board(i)=B(1); score_board(i-4)=B(2);score_board(i-8)=B(3); score_board(i-12)=B(4);totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase 'right'C=score_board;for i=4:4:16A=[score_board(i) score_board(i-1) score_board(i-2) score_board(i-3)];[B score]=move(A);score_board(i)=B(1); score_board(i-1)=B(2);score_board(i-2)=B(3); score_board(i-3)=B(4); totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase 'left'C=score_board;for i=1:4:13A=[score_board(i) score_board(i+1) score_board(i+2) score_board(i+3)];[B score]=move(A);score_board(i)=B(1); score_board(i+1)=B(2);score_board(i+2)=B(3); score_board(i+3)=B(4); totalscore=totalscore+score;endif C==score_boardelseg2048('show');g2048('addnum') ;pause(0.2);g2048('show');endcase'addnum'num_0=find(score_board==0);l=length(num_0);if l>0score_board(num_0(ceil(l*rand)))=2+2*(rand<0.1);endendendfunction Y=addnum(X)num_0=find(X==0);l=length(num_0);X(num_0(ceil(l*rand)))=2+2*(rand<0.1);Y=X;endfunction [B score]=move(A)score=0;for k=1:2for i=1:3if A(i)==0for j=i:3A(j)=A(j+1);endA(4)=0;endendendif A(1)==A(2)if A(3)==A(4)A(1)=A(1)+A(2);A(2)=A(3)+A(4);A(3)=0;A(4)=0;score=A(1)+A(2); elseA(1)=A(1)+A(2);A(2)=A(3);A(3)=A(4);A(4)=0;score=A(1);endelse if A(2)==A(3)A(1)=A(1);A(2)=A(2)+A(3);A(3)=A(4);A(4)=0;score=A(2);else if A(3)==A(4)A(1)=A(1);A(2)=A(2);A(3)=A(3)+A(4);A(4)=0;score=A(3); else score=0; endendendB=A;End5.俄罗斯方块%各个函数请分开写if nargin == 0OldHandle = findobj( 'Type', 'figure', 'Tag', 'RussiaBlock' ) ;if ishandle( OldHandle )delete( OldHandle ) ;endFigureHandle = figure( 'Name', '俄罗斯方块MATLAB版', 'Tag', 'RussiaBlock', 'NumberTitle', 'off',...'Menubar', 'none', 'DoubleBuffer', 'on', 'Resize', 'off', 'visible', 'on',...'KeyPressFcn', 'RussiaBlock( ''KeyPress_Callback'', gcbo )',...'HelpFcn', 'helpdlg(''帮不了你- -!'',''不好意思'')',...'CloseRequestFcn', 'RussiaBlock( ''CloseFigure_Callback'', gcbo )' ) ;generate_FigureContent( FigureHandle ) ;init_FigureContent( FigureHandle ) ;set( FigureHandle, 'Visible', 'on' ) ;elseif ischar( varargin{1} )feval( varargin{:} ) ;end% -------------------------------------------------------------------------function generate_FigureContent( FigureHandle )TabSpace = 30 ;BlockWidth = 20 ;BlockHeight = 20 ;FigureWidth = BlockWidth * (12 + 1) + TabSpace * 7;FigureHeight = 500 ;set( FigureHandle, 'Position', [0 0 FigureWidth FigureHeight] ) ;movegui( FigureHandle, 'center' ) ;% 创建菜单BeginMenu = uimenu( FigureHandle, 'Label', '开始' ) ;StartMenu = uimenu( BeginMenu, 'Label', '开始新游戏', 'Accelerator', 'N',...'Callback', 'RussiaBlock( ''StartNewGame_Callback'', gcbo )');SaveMenu = uimenu( BeginMenu, 'Label', '保存', 'Accelerator', 'S', 'Enable', 'off',...'Separator', 'on', 'Cal', 'RussiaBlock( ''SaveGame_Callback'', gcbo )' );LoadMenu = uimenu( BeginMenu, 'Label', '读取', 'Accelerator', 'L', 'Enable', 'off',...'Cal', 'RussiaBlock( ''LoadGame_Callback'', gcbo )' );QuitMenu = uimenu( BeginMenu, 'Label', '退出', 'Accelerator', 'Q', 'Separator', 'on', 'Cal', 'close(gcf)');OperationMenu = uimenu( FigureHandle, 'Label', '功能' );BoardConfigMenu = uimenu( OperationMenu, 'label', '键盘设置', 'Enable', 'off',...'Cal', 'RussiaBlock( ''BoardConfig_Callback'', gcbo )' );FigureConfigMenu = uimenu( OperationMenu, 'label', '界面设置', 'Enable', 'off',...'Cal', 'RussiaBlock( ''FigureConfig_Callback'', gcbo )' );HighScoreMenu = uimenu( OperationMenu, 'label', '最高记录', 'Separator', 'on',...'Cal', 'RussiaBlock( ''HighScore_Callback'', gcbo )', 'Enable', 'off' );GameLevelMenu = uimenu( OperationMenu, 'Label', '游戏难度',...'Cal','RussiaBlock( ''GameLevel_Callback'', gcbo )' );HelpMenu = uimenu( FigureHandle, 'Label', '帮助' );AboutMenu = uimenu( HelpMenu, 'Label', '关于此软件', 'Cal', 'helpdlg(''俄罗斯方块MATLAB版------冰风漫天(制作)(2006/11/21)'',''关于此软件……'')');HelpDlgMenu = uimenu( HelpMenu, 'Label', '游戏帮助', 'Separator', 'on', 'Cal', 'helpdlg(''帮不了你- -!'',''不好意思'')' );% 创建工具条,图标可以用imread从图片读取,但图片不要太大BeginTool = uipushtool( 'ToolTipString', '开始', 'CData', rand(16,16,3), 'Tag', 'BeginTool',...'ClickedCallback', 'RussiaBlock( ''StartNewGame_Callback'', gcbo )' ) ;PauseTool = uitoggletool( 'ToolTipString', '暂停', 'Tag', 'PauseTool', 'Tag', 'PauseTool',...'CData', reshape( repmat( [1 1 0], 16, 16), [16,16,3] ),...'ClickedCallback', 'RussiaBlock( ''PauseGame_Callback'', gcbo )' ) ;% 创建游戏窗口MainWindowXPos = TabSpace;MainWindowYPos = TabSpace;MainWindowWidth = BlockWidth * 12 ;MainWindowHeight = BlockHeight * 22 ;MainWindowPosition = [MainWindowXPos MainWindowYPos MainWindowWidth MainWindowHeight] ;% 定义游戏窗口的右键菜单AxesContextMenu = uicontextmenu( 'Tag', 'uicontextmenu' ) ;uimenu( AxesContextMenu, 'Label', '设置窗口颜色', 'Cal', 'RussiaBlock( ''WindowColor_Callback'', gcbo )' )uimenu( AxesContextMenu, 'Label', '设置背景图片', 'Cal', 'RussiaBlock( ''WindowPicture_Callback'', gcbo )' )uimenu( AxesContextMenu, 'Label', '设置方块颜色', 'Cal', 'RussiaBlock( ''BlockColor_Callback'', gcbo )' )uimenu( AxesContextMenu, 'Label', '恢复默认', 'Cal', 'RussiaBlock( ''Default_Callback'', gcbo )' )。

相关文档
最新文档