Python实现的人机对战小游戏

合集下载

python实例:利用pygame实现小游戏“飞机大战”

python实例:利用pygame实现小游戏“飞机大战”

python实例:利⽤pygame实现⼩游戏“飞机⼤战”0、程序代码代码1:1import random2import pygame34# 屏幕⼤⼩的常量5 SCREEN_RECT = pygame.Rect(0, 0, 480, 700)6# 刷新的帧率7 FRAME_PER_SEC = 608# 创建敌机的定时器常量9 CREATE_ENEMY_EVENT = EREVENT10# 英雄发射⼦弹事件11 HERO_FIRE_EVENT = EREVENT+112#⼦弹速度13 BULLET_SPEED = -2.5141516class GameSprite(pygame.sprite.Sprite):17""""飞机⼤战游戏精灵"""1819def__init__(self, image_name, speed = 1):20# 调⽤⽗亲的初始化⽅法21 super().__init__()22# 定义对象的属性23 self.image = pygame.image.load(image_name)24 self.rect = self.image.get_rect()25 self.speed = speed2627def update(self):28#在屏幕的垂直⽅向上移动29 self.rect.y += self.speed303132class Background(GameSprite):33""""游戏背景精灵"""3435def__init__(self, is_alt = False):36# 1.调⽤⽗类构造⽅法37 super().__init__("./images/background.png")38# 2.判断是否与前图像循环重合,若否,则需重新设置初始位置39if is_alt:40 self.rect.y = -self.rect.height414243def update(self):44# 1.调⽤⽗类的⽅法,,,注意super后⾯要加括号!!!45 super().update()46# 2.判断是否移出屏幕47if self.rect.y >= SCREEN_RECT.height:48 self.rect.y = -self.rect.height495051class Enemy(GameSprite):52""""敌机精灵"""5354def__init__(self):55# 1.调⽤⽗类⽅法,创建敌机精灵56 super().__init__("./images/enemy1.png")57# 2. 指定敌机的初始随机速度 1-2-358 self.speed = random.randint(1,3)59# 3.指定敌机的初始随机位置60 self.rect.bottom = 06162 max_x = SCREEN_RECT.width - self.rect.width63 self.rect.x = random.randint(0, max_x)646566def update(self):6768# 1.调⽤⽗类⽅法,保持垂直⽅向的飞⾏69 super().update()70# 2.判断是否⾮出屏幕,如果是,需要从精灵组删除敌机71if self.rect.y >= SCREEN_RECT.height:72#print("飞出屏幕,需要从精灵组删除...")73# kill⽅法可以将精灵从精灵组中移除74 self.kill()7576def__del__(self):77#print("敌机挂了%s" %self.rect)78pass798081class Hero(GameSprite):82"""英雄精灵"""8384def__init__(self):85# 1.调⽤⽗类⽅法,设置image和speed86 super().__init__("./images/me1.png", speed = 0)87 self.speed1 = 088# 2.设置英雄的初始位置89 self.rect.centerx = SCREEN_RECT.centerx90 self.rect.bottom = SCREEN_RECT.bottom - 10091# 3.创建⼦弹精灵组92 self.bullets = pygame.sprite.Group()9394def update(self):95#(错误的判断句,会导致⼀旦出界就很难再恢复回来)if 0 <= self.rect.x <= SCREEN_RECT.width - self.rect.width: 96 self.rect.x += self.speed97if self.rect.x < 0:98 self.rect.x = 099elif self.rect.right > SCREEN_RECT.width:100 self.rect.right = SCREEN_RECT.width101102 self.rect.y += self.speed1103if self.rect.y < 0:104 self.rect.y = 0105elif self.rect.bottom > SCREEN_RECT.height:106 self.rect.bottom = SCREEN_RECT.height107108109def fire(self):110#print("发射⼦弹")111# 1.创建⼦弹精灵112 bullet = Bullet()113# 2.设置精灵位置114 bullet.rect.bottom = self.rect.y115 bullet.rect.centerx = self.rect.centerx116# 3.将精灵添加到精灵组117 self.bullets.add(bullet)118119120class Bullet(GameSprite):121""""⼦弹精灵"""122123def__init__(self):124# 调⽤⽗类⽅法125 super().__init__("./images/bullet1.png", BULLET_SPEED)126127def update(self):128 super().update()129if self.rect.bottom < 0:130 self.kill()131132def__del__(self):133#print("⼦弹被销毁")134passView Code代码2:1from plane_sprites import *2# 游戏主程序34class PlaneGame(object):5""""飞机⼤战主游戏"""67def__init__(self):8print("游戏初始化")910# 1.创建游戏的窗⼝11 self.screen = pygame.display.set_mode(SCREEN_RECT.size)12# 2.创建游戏的时钟13 self.clock = pygame.time.Clock()14# 3.调⽤私有⽅法,精灵和精灵组的创建15 self.__create_sprites()16# 4.设置定时器事件——创建敌机 1s17 pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)18 pygame.time.set_timer(HERO_FIRE_EVENT, 300)1920def__create_sprites(self):21# 创建背景精灵和精灵组22 bg1 = Background()23 bg2 = Background(True)24 self.back_group = pygame.sprite.Group(bg1, bg2)25# 创建敌机精灵26 self.enemy_group = pygame.sprite.Group()27# 创建英雄精灵28 self.hero = Hero()29 self.hero_group = pygame.sprite.Group(self.hero)303132def start_game(self):33print("游戏开始...")3435while True:36# 1.设置刷新帧率37 self.clock.tick(FRAME_PER_SEC)38# 2.事件监听39 self.__event_handler()40# 3.碰撞检测41 self.__check_collide()42# 4.更新/绘制精灵组43 self.__update_sprites()44# 5.更新显⽰45 pygame.display.update()464748def__event_handler(self):49for event in pygame.event.get():50#判断是否退出游戏51if event.type == pygame.QUIT:52 PlaneGame.__game_over()53elif event.type == CREATE_ENEMY_EVENT:54#print("敌机出现。

python飞机大战代码

python飞机大战代码

python飞机大战代码以下是一个简单的 python 飞机大战游戏的代码示例:```python。

import pygame。

import random。

# 初始化 Pygame。

pygame.init()。

#设置游戏窗口大小和标题。

WINDOW_WIDTH=640。

WINDOW_HEIGHT=480。

screen = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))。

pygame.display.set_caption("飞机大战")。

#加载背景图片。

background_img =pygame.image.load("background.jpg").convert()。

#加载玩家飞机图片和音效。

player_img = pygame.image.load("player.png").convert_alpha()。

player_explosion_sound = pygame.mixer.Sound("explosion.wav")。

#加载敌机图片和音效。

enemy_img = pygame.image.load("enemy.png").convert_alpha()。

enemy_explosion_sound = pygame.mixer.Sound("explosion.wav")。

#加载子弹图片和音效。

bullet_img = pygame.image.load("bullet.png").convert_alpha()。

bullet_sound = pygame.mixer.Sound("bullet.wav")。

#定义玩家飞机和敌机的初始位置和速度。

player_x = 300。

python实现飞机大战游戏(pygame版)

python实现飞机大战游戏(pygame版)

python实现飞机⼤战游戏(pygame版)简介使⽤python实现pygame版的飞机⼤战游戏;环境:Windows系统+python3.8.0游戏规则:1.点击“PLAY”或者按键“P”开始游戏;2.敌机根据设置频率从顶部随机位置⽣成,⽣成后向下移动;3.飞船在底部中间⽣成,玩家使⽤上下左右键控制飞船移动,敲击空格键发射⼦弹;4.⼦弹打到敌机,该敌机产⽣爆炸效果并累计分数到右上⾓;5.消灭10只飞机后,等级升⾼,敌机⽣成频率变快,下落速度也变快;6.当三条命都消失了,游戏结束。

游戏运⾏效果如下:实现过程1.新建⽂件“file.py”,⽤来存储信息到⽂件和读取⽂件的信息,本例⽤来存储和读取最⾼分;import pickle# filename = 'file/stats.pkl'# 存储信息到⽂件def save_file(obj, filename):statsObj = load_file(filename)if statsObj == 0:# 不存在⽂件时,直接保存字典with open(filename, 'wb') as f:pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)else:# 存在⽂件时,只修改⽂件中的最⾼分for key, val in statsObj.items():# 获取⽂件最⾼分的值(当⽂件字段不⽌⼀个时候使⽤)if key == 'highScore':statsObj[key] = obj['highScore']obj = statsObjwith open(filename, 'wb') as f:pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)# 读取信息def load_file(filename):try:with open(filename, 'rb') as f:return pickle.load(f)except FileNotFoundError:# 不存在⽂件则输⼊错误信息msg = "Sorry, the file " + filename + " does not exist."print(msg)return 0# obj = {'highScore': 20, 'points': 5}# obj = {'highScore': 50}# save_file(obj, filename)# filedata = load_file(filename)# print(filedata)2.k新建⽂件settings.py,⽤来定义⼀些必须的基本属性和初始值;import file as fclass Settings():def __init__(self):self.screen_width = 480self.screen_height = 660self.bg_color = (230, 230, 230)# ⼦弹设置(宽、⾼、颜⾊、最⼤数量)self.bullet_width = 5self.bullet_height = 15self.bullet_color = 255, 255, 255# 敌机移动频率self.enemy_frequency = 0# 加快游戏节奏的速度self.speedup_scale = 1.1# 分数的提⾼速度self.score_scale = 1.5self.initialize_settings()# 初始化统计信息self.reset_stats()# 统计信息⽂件路径self.filename = 'file/stats.pkl'# 游戏刚启动时处于⾮活动状态self.game_active = False# 读取⽂件的最⾼分,在任何情况下都不应重置最⾼得分statsObj = f.load_file(self.filename)if statsObj == 0:# 不存在⽂件则显⽰最⾼分0highScore = 0else:for key, val in statsObj.items():# 获取⽂件最⾼分的值(当⽂件字段不⽌⼀个时候使⽤)if key == 'highScore':highScore = valself.high_score = highScoredef initialize_settings(self):"""初始化随游戏进⾏⽽变化的设置"""self.player_move_speed = 2.5self.bullet_speed = 3self.enemy_move_speed = 1# 记分self.one_points = 50def increase_speed(self):"""提⾼速度设置"""# self.player_move_speed *= self.speedup_scaleself.bullet_speed *= self.speedup_scaleself.enemy_move_speed *= self.speedup_scaleself.one_points = int(self.one_points * self.score_scale)def reset_stats(self):"""初始化在游戏运⾏期间可能变化的统计信息"""# 可射失的数量self.player_limit = 3# 射击分数self.score = 0# 等级self.level = 1# 打中多少矩形升⼀级self.level_number = 10# ⽣成敌机频率间隔self.enemy_frequency_space = 503.新建⽂件enemy.py,⽤来定义敌机类(位置topleft随机⽣成)和声明⽅法move;import pygameimport randomfrom pygame.sprite import Spriteclass Enemy(Sprite):def __init__(self, enemy_down_imgs, settings):super(Enemy, self).__init__()self.image = pygame.image.load('images/enemy1.png')self.rect = self.image.get_rect()self.rect.topleft = [random.randint(0, settings.screen_width - self.rect.width), 0]self.down_imgs = enemy_down_imgsself.speed = settings.enemy_move_speedself.down_index = 0# 敌机移动,边界判断及删除在游戏主循环⾥处理def move(self):self.rect.top += self.speed4.新建⽂件player.py,⽤来定义玩家类(可上下左右移动)和相应的⽅法;import pygamefrom pygame.sprite import Spriteclass Player(Sprite):def __init__(self, settings, screen):super(Player, self).__init__()self.settings = settingsself.screen = screenself.screen_rect = self.screen.get_rect()# 引⼊飞船图⽚并定位self.image = pygame.image.load('images/player.png')self.rect = self.image.get_rect()self.rect.centerx = self.screen_rect.centerxself.rect.bottom = self.screen_rect.bottom# 移动标志self.move_left = Falseself.move_right = Falseself.move_down = Falseself.move_up = Falsedef rotate(self, angle):# 图⽚旋转self.image = pygame.transform.rotate(self.image, angle)def scale(self, multiple):# 图⽚缩放self.image = pygame.transform.smoothscale(self.image, (multiple, multiple))def update(self):if self.move_left and self.rect.left > self.screen_rect.left:self.rect.centerx -= self.settings.player_move_speedif self.move_right and self.rect.right < self.screen_rect.right:self.rect.centerx += self.settings.player_move_speedif self.move_down and self.rect.bottom < self.screen_rect.bottom:self.rect.centery += self.settings.player_move_speedif self.move_up and self.rect.top > 0:self.rect.centery -= self.settings.player_move_speeddef draw_player(self):"""绘制飞船到屏幕"""self.screen.blit(self.image, self.rect)5.新建⽂件“bullet.py”,⽤来定义⼦弹类(位置在飞船的顶部,并往上移动)和相应的⽅法;import pygamefrom pygame.sprite import Spriteclass Bullet(Sprite):""" ⼀个对飞船发射的⼦弹进⾏管理的类 """def __init__(self, settings, screen, player):""" 在飞船所处的位置创建⼀个⼦弹对象 """super(Bullet, self).__init__()self.screen = screen# 在 (0,0) 处创建⼀个表⽰⼦弹的矩形,再设置正确的位置self.rect = pygame.Rect(0, 0, settings.bullet_width, settings.bullet_height)self.rect.centerx = player.rect.centerx# 飞船顶部self.rect.bottom = player.rect.top# 存储⽤⼩数表⽰的⼦弹位置self.y = float(self.rect.y)self.color = settings.bullet_colorself.speed = settings.bullet_speeddef update(self):"""向上移动⼦弹"""# 更新表⽰⼦弹位置的⼩数值(⼦弹往右)self.y -= self.speed# 更新表⽰⼦弹的rect的位置self.rect.y = self.ydef draw_bullet(self):"""在屏幕上绘制⼦弹"""pygame.draw.rect(self.screen, self.color, self.rect)6.新建⽂件“button.py”,⽤来定义按钮类和相应⽅法,本例使⽤于绘制“PLAY”按钮;import pygame.fontclass Button():def __init__(self, screen, msg):"""初始化按钮的属性"""self.screen = screenself.screen_rect = screen.get_rect()# 设置按钮的尺⼨和其他属性self.width, self.height = 100, 30self.button_color = (216, 30, 6)self.text_color = (255, 255, 255)self.font = pygame.font.SysFont(None, 36)# 创建按钮的rect对象,并使其居中self.rect = pygame.Rect(0, 0, self.width, self.height)self.rect.center = self.screen_rect.center# 按钮的标签只需创建⼀次self.prep_msg(msg)def prep_msg(self, msg):"""将msg渲染为图像,并使其在按钮上居中"""self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)self.msg_image_rect = self.msg_image.get_rect()self.msg_image_rect.center = self.rect.centerdef draw_button(self):# 绘制⼀个⽤颜⾊填充的按钮,再绘制⽂本self.screen.fill(self.button_color, self.rect)self.screen.blit(self.msg_image, self.msg_image_rect)7.新建⽂件“scoreboard.py”,⽤来定义记分板,本例使⽤于绘制左上⾓飞船(⽣命数)、顶部中间的“最⾼分”、右上⾓的“积分”和“等级”;import pygame.fontfrom pygame.sprite import Groupfrom player import Playerclass Scoreboard():"""显⽰得分信息的类"""def __init__(self, settings, screen):"""初始化显⽰得分涉及的属性"""self.screen = screenself.screen_rect = screen.get_rect()self.settings = settings# 显⽰得分信息时使⽤的字体设置self.text_color = (255, 255, 255)self.font = pygame.font.SysFont(None, 30)# 飞船缩放值self.scaleValue = 20# 准备初始得分图像\最⾼得分\等级self.prep_score()self.prep_high_score()self.prep_level()self.prep_players()def prep_score(self):"""将得分转换为渲染的图像"""rounded_score = int(round(self.settings.score, -1))score_str = '{:,}'.format(rounded_score)self.score_image = self.font.render(score_str, True, self.text_color)# 将得分放在屏幕右上⾓self.score_rect = self.score_image.get_rect()self.score_rect.right = self.screen_rect.right -20self.score_rect.top = 10def prep_high_score(self):""" 将最⾼得分转换为渲染的图像 """high_score = int(round(self.settings.high_score, -1))high_score_str = "{:,}".format(high_score)self.high_score_image = self.font.render(high_score_str, True, self.text_color)# 将最⾼得分放在屏幕顶部中央self.high_score_rect = self.high_score_image.get_rect()self.high_score_rect.centerx = self.screen_rect.centerxself.high_score_rect.top = self.score_rect.topdef prep_level(self):"""将等级转换为渲染的图像"""self.level_image = self.font.render(str(self.settings.level), True, self.text_color)# 将等级放在得分下⽅self.level_rect = self.level_image.get_rect()self.level_rect.right = self.score_rect.rightself.level_rect.top = self.score_rect.bottom + 10def prep_players(self):""" 显⽰还余下多少艘飞船 """self.players = Group()for player_number in range(self.settings.player_limit):player = Player(self.settings, self.screen)# 缩放球⼤⼩并赋值位置player.scale(self.scaleValue)player.rect.x = 10 + player.rect.width * player_number * 0.5player.rect.y = self.score_rect.topself.players.add(player)def show_score(self):"""在屏幕上显⽰得分"""self.screen.blit(self.score_image, self.score_rect)self.screen.blit(self.high_score_image, self.high_score_rect)self.screen.blit(self.level_image, self.level_rect)# 绘制飞船self.players.draw(self.screen)8.新建⽂件“game_functions.py”,存放跟游戏有关的所有业务逻辑函数(代码有详细的注释信息);import sysimport pygamefrom bullet import Bulletfrom enemy import Enemyimport file as f# 事件def check_events(settings, screen, player, play_button, scoreboard, bullets, fireSound):""" 响应按键和⿏标事件 """for event in pygame.event.get():if event.type == pygame.QUIT:save_file(settings)sys.exit()elif event.type == pygame.KEYDOWN:check_keydown_events(event, settings, screen, player, scoreboard, bullets, fireSound)elif event.type == pygame.KEYUP:check_keyup_events(event, player)elif event.type == pygame.MOUSEBUTTONDOWN:mouse_x, mouse_y = pygame.mouse.get_pos()check_play_button(settings, play_button, scoreboard, mouse_x, mouse_y)def check_keydown_events(event, settings, screen, player, scoreboard, bullets, fireSound):""" 响应按键 """if event.key == pygame.K_DOWN:player.move_down = Trueelif event.key == pygame.K_UP:player.move_up = Trueelif event.key == pygame.K_LEFT:player.move_left = Trueelif event.key == pygame.K_RIGHT:player.move_right = Trueelif event.key == pygame.K_SPACE:fireSound.play()# 点击空格键创建⼀颗⼦弹fire_bullet(settings, screen, player, bullets)elif event.key == pygame.K_p:start_game(settings, scoreboard)elif event.key == pygame.K_q:save_file(settings)sys.exit()def check_keyup_events(event, player):""" 响应松开 """if event.key == pygame.K_DOWN:player.move_down = Falseelif event.key == pygame.K_UP:player.move_up = Falseelif event.key == pygame.K_LEFT:player.move_left = Falseelif event.key == pygame.K_RIGHT:player.move_right = Falsedef check_play_button(settings, play_button, scoreboard, mouse_x, mouse_y):"""在玩家单击Play按钮时开始新游戏"""button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)if button_clicked and not settings.game_active:start_game(settings, scoreboard)def start_game(settings, scoreboard):"""开始游戏"""# 重置游戏设置settings.initialize_settings()# 隐藏光标pygame.mouse.set_visible(False)# 重置游戏统计信息settings.reset_stats()settings.game_active = True# 重置记分牌图像scoreboard.prep_score()scoreboard.prep_high_score()scoreboard.prep_level()scoreboard.prep_players()def save_file(settings):# 保持⽂件obj = {'highScore': settings.high_score}f.save_file(obj, settings.filename)# 敌机def update_enemies(settings, screen, scoreboard, enemies, enemies_down, enemy_down_imgs, player, bullets, explosiveSound): # ⽣成敌机,需要控制⽣成频率if settings.enemy_frequency % settings.enemy_frequency_space == 0:enemy1 = Enemy(enemy_down_imgs, settings)enemies.add(enemy1)settings.enemy_frequency += 1if settings.enemy_frequency >= 100:settings.enemy_frequency = 0for enemy in enemies:# 移动敌机enemy.move()# 敌机与玩家飞机碰撞效果处理两个精灵之间的圆检测if pygame.sprite.collide_circle(enemy, player):enemies_down.add(enemy)enemies.remove(enemy)settings.player_limit -= 1scoreboard.prep_players()break# 移动出屏幕后删除飞机if enemy.rect.top < 0:enemies.remove(enemy)# 敌机被⼦弹击中效果处理# 将被击中的敌机对象添加到击毁敌机 Group 中,⽤来渲染击毁动画# ⽅法groupcollide()是检测两个精灵组中精灵们的矩形冲突enemies1_down = pygame.sprite.groupcollide(enemies, bullets, True, True)if enemies1_down:explosiveSound.play()# 计算分数并渲染for enemys in enemies1_down.values():settings.score += settings.one_points * len(enemys)scoreboard.prep_score()# 渲染最⾼分check_high_score(settings, scoreboard)# 等达到等级数量升级并渲染新等级settings.level_number -= 1if settings.level_number == 0:settings.increase_speed()settings.level += 1scoreboard.prep_level()# 还原为4(同settings⼀致)settings.level_number = 10# 加快⽣成敌机if settings.enemy_frequency_space > 10:settings.enemy_frequency_space -= 10# 遍历key值返回的碰撞敌机for enemy_down in enemies1_down:# 点击销毁的敌机到列表enemies_down.add(enemy_down)# 敌机被⼦弹击中效果显⽰for enemy_down in enemies_down:if enemy_down.down_index == 0:passif enemy_down.down_index > 7:enemies_down.remove(enemy_down)continue#显⽰碰撞图⽚screen.blit(enemy_down.down_imgs[enemy_down.down_index // 2], enemy_down.rect) enemy_down.down_index += 1# 显⽰精灵enemies.draw(screen)# ⼦弹def fire_bullet(settings, screen, player, bullets):"""创建⼦弹"""new_bullet = Bullet(settings, screen, player)bullets.add(new_bullet)def update_bullets(screen, bullets):"""更新⼦弹的位置,并删除已消失的⼦弹"""# 更新⼦弹的位置bullets.update()# 删除已消失的⼦弹并同时更新飞船的⽣命for bullet in bullets.copy():if bullet.rect.top < screen.get_rect().top:bullets.remove(bullet)# 分数def check_high_score(settings, scoreboard):"""检查是否诞⽣了新的最⾼得分"""if settings.score > settings.high_score:settings.high_score = settings.scorescoreboard.prep_high_score()# 屏幕def update_screen(settings, screen, player, play_button, scoreboard, enemies, bullets): """ 更新屏幕上的图像,并切换到新屏幕 """# 绘制飞船到屏幕player.draw_player()# 绘制⼦弹到屏幕for bullet in bullets.sprites():bullet.draw_bullet()# 渲染记分牌信息scoreboard.show_score()#if settings.player_limit == 0:settings.game_active = Falsesettings.reset_stats()# 清空矩形列表和⼦弹列表enemies.empty()bullets.empty()screen_rect = screen.get_rect()player.rect.centerx = screen_rect.centerxplayer.rect.bottom = screen_rect.bottom# 如果游戏处于⾮活动状态,就绘制 Play 按钮if not settings.game_active:play_button.draw_button()# 让最近绘制的屏幕可见pygame.display.flip()9.新建⽂件shootingenemy.py,主函数⽤来初始化程序,并同步更新程序的信息;import pygamefrom pygame.sprite import Groupfrom settings import Settingsfrom button import Buttonfrom player import Playerimport game_functions as gffrom scoreboard import Scoreboarddef run_game():pygame.init()# 初始化全部⾳频,并加载爆炸声⾳乐pygame.mixer.init()# 等待1spygame.time.delay(1000)pygame.mixer.music.load('file/bgsound.mp3')# -1代表⽆限循环(背景⾳乐)pygame.mixer.music.play(-1)# 爆炸声explosiveSound = pygame.mixer.Sound('file/explosiveSound.wav')# 枪声fireSound = pygame.mixer.Sound('file/fireSound.wav')# 游戏循环帧率设置clock = pygame.time.Clock()settings = Settings()screen = pygame.display.set_mode((settings.screen_width, settings.screen_height))# 全屏显⽰# screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)pygame.display.set_caption('飞机⼤战')# 左上⾓图标ic_launcher = pygame.image.load('images/ic_launcher.png').convert_alpha()pygame.display.set_icon(ic_launcher)# 背景图background = pygame.image.load('images/background.png').convert_alpha()# 敌机图⽚enemy_img1= pygame.image.load('images/enemy1.png')enemy_img2= pygame.image.load('images/enemy2.png')enemy_img3= pygame.image.load('images/enemy3.png')enemy_img4= pygame.image.load('images/enemy4.png')# 敌机不同状态的图⽚列表,多张图⽚展⽰为动画效果enemy_down_imgs = []enemy_down_imgs.append(enemy_img1)enemy_down_imgs.append(enemy_img2)enemy_down_imgs.append(enemy_img3)enemy_down_imgs.append(enemy_img4)# 储存敌机enemies = Group()# 存储被击毁的飞机,⽤来渲染击毁动画enemies_down = Group()# 创建Play按钮play_button = Button(screen, 'Play')# 创建飞船player = Player(settings, screen)# 创建⼦弹的编组bullets = Group()# 创建记分牌scoreboard = Scoreboard(settings, screen)while True:# 绘制背景screen.blit(background, (0, 0))# 控制游戏最⼤频率clock.tick(60)# 检查玩家输⼊(不加会导致⼀直加载)gf.check_events(settings, screen, player, play_button, scoreboard, bullets, fireSound)if settings.game_active:# 更新飞船位置player.update()# 更新敌机gf.update_enemies(settings, screen, scoreboard, enemies, enemies_down, enemy_down_imgs, player, bullets, explosiveSound)# 更新⼦弹位置gf.update_bullets(screen, bullets)# 更新屏幕信息gf.update_screen(settings, screen, player, play_button, scoreboard, enemies, bullets)run_game(),10.在⽂件shootingenemy.py⽬录路径下,执⾏命令“python shootingenemy.py”弹出窗⼝,即可对其操作游玩。

Python小游戏代码:飞机大战(超详细)

Python小游戏代码:飞机大战(超详细)

Python⼩游戏代码:飞机⼤战(超详细)我⽤的是pycharm,⼤家可以⽤别的Python编辑器。

创建⼀个新的⽂件夹,把图⽚的⽂件夹导⼊,图⽚的链接我放下⾯了,⼤家⾃取。

提取码:Leo1在刚才的⽂件夹⾥新建Python⽂件,输⼊以下代码# coding:utf-8import pygame, sys, random, time, easyguifrom pygame.locals import *# 初始化pygame环境pygame.init()# 创建⼀个长宽分别为480/650窗⼝canvas = pygame.display.set_mode((480, 650))canvas.fill((255, 255, 255))# 设置窗⼝标题pygame.display.set_caption("飞机⼤战")bg = pygame.image.load("images/bg1.png")enemy1 = pygame.image.load("images/enemy1.png")enemy2 = pygame.image.load("images/enemy2.png")enemy3 = pygame.image.load("images/enemy3.png")b = pygame.image.load("images/bullet1.png")h = pygame.image.load("images/hero.png")#开始游戏图⽚startgame=pygame.image.load("images/startGame.png")#logo图⽚logo=pygame.image.load("images/LOGO.png")#暂停图⽚pause = pygame.image.load("images/game_pause_nor.png")# 添加时间间隔的⽅法def isActionTime(lastTime, interval):if lastTime == 0:return TruecurrentTime = time.time()return currentTime - lastTime >= interval# 定义Sky类class Sky():def __init__(self):self.width = 480self.height = 852self.img = bgself.x1 = 0self.y1 = 0self.x2 = 0self.y2 = -self.height# 创建paint⽅法def paint(self):canvas.blit(self.img, (self.x1, self.y1))canvas.blit(self.img, (self.x2, self.y2))# 创建step⽅法def step(self):self.y1 = self.y1 + 1self.y2 = self.y2 + 1if self.y1 > self.height:self.y1 = -self.heightif self.y2 > self.height:self.y2 = -self.height# 定义⽗类FlyingObjectclass FlyingObject(object):def __init__(self, x, y, width, height, life, img):self.x = xself.y = yself.width = widthself.height = heightself.life = lifeself.img = img# 敌飞机移动的时间间隔stTime = 0self.interval = 0.01# 添加删除属性self.canDelete = False# 定义paint⽅法def paint(self):canvas.blit(self.img, (self.x, self.y))# 定义step⽅法def step(self):# 判断是否到了移动的时间间隔if not isActionTime(stTime, self.interval):returnstTime = time.time()# 控制移动速度self.y = self.y + 2# 定义hit⽅法判断两个对象之间是否发⽣碰撞def hit(self, component):c = componentreturn c.x > self.x - c.width and c.x < self.x + self.width and \ c.y > self.y - c.height and c.y < self.y + self.height# 定义bang⽅法处理对象之间碰撞后的处理def bang(self, bangsign):# 敌机和英雄机碰撞之后的处理if bangsign:if hasattr(self, 'score'):GameVar.score += self.scoreif bangsign == 2:self.life -= 1# 设置删除属性为Trueself.canDelete = True# 敌机和⼦弹碰撞之后的处理else:self.life -= 1if self.life == 0:# 设置删除属性为Trueself.canDelete = Trueif hasattr(self, 'score'):GameVar.score += self.score# 定义outOfBounds⽅法判断对象是否越界def outOfBounds(self):return self.y > 650# 重构Enemy类class Enemy(FlyingObject):def __init__(self, x, y, width, height, type, life, score, img):FlyingObject.__init__(self, x, y, width, height, life, img)self.type = typeself.score = score# 重构Hero类class Hero(FlyingObject):def __init__(self, x, y, width, height, life, img):FlyingObject.__init__(self, x, y, width, height, life, img)self.x = 480 / 2 - self.width / 2self.y = 650 - self.height - 30self.shootLastTime = 0self.shootInterval = 0.3def shoot(self):if not isActionTime(self.shootLastTime, self.shootInterval):returnself.shootLastTime = time.time()GameVar.bullets.append(Bullet(self.x + self.width / 2 - 5, self.y - 10, 10, 10, 1, b))# 重构Bullet类class Bullet(FlyingObject):def __init__(self, x, y, width, height, life, img):FlyingObject.__init__(self, x, y, width, height, life, img)def step(self):self.y = self.y - 2# 重写outOfBounds⽅法判断⼦弹是否越界def outOfBounds(self):return self.y < -self.height# 创建componentEnter⽅法def componentEnter():# 随机⽣成坐标x = random.randint(0, 480 - 57)x1 = random.randint(0, 480 - 50)x2 = random.randint(0, 480 - 100)# 根据随机整数的值⽣成不同的敌飞机n = random.randint(0, 9)# 判断是否到了产⽣敌飞机的时间if not isActionTime(stTime, GameVar.interval):returnstTime = time.time()if n <= 7:GameVar.enemies.append(Enemy(x, 0, 57, 45, 1, 1, 1, enemy1))elif n == 8:GameVar.enemies.append(Enemy(x1, 0, 50, 68, 2, 3, 5, enemy2))elif n == 9:if len(GameVar.enemies) == 0 or GameVar.enemies[0].type != 3:GameVar.enemies.insert(0, Enemy(x2, 0, 100, 153, 3, 10, 20, enemy3))# 创建画组件⽅法def componentPaint():# 判断是否到了飞⾏物重绘的时间if not isActionTime(GameVar.paintLastTime, GameVar.paintInterval):returnGameVar.paintLastTime = time.time()# 调⽤sky对象的paint⽅法GameVar.sky.paint()for enemy in GameVar.enemies:enemy.paint()# 画出英雄机GameVar.hero.paint()# 画出⼦弹对象for bullet in GameVar.bullets:bullet.paint()# 写出分数和⽣命值renderText('SCORE:' + str(GameVar.score), (0, 0))renderText('LIFE:' + str(GameVar.heroes), (380, 0))# 创建组件移动的⽅法def componentStep():# 调⽤sky对象的step⽅法GameVar.sky.step()for enemy in GameVar.enemies:enemy.step()# 使⼦弹移动for bullet in GameVar.bullets:bullet.step()# 创建删除组件的⽅法def componentDelete():for enemy in GameVar.enemies:if enemy.canDelete or enemy.outOfBounds():GameVar.enemies.remove(enemy)for bullet in GameVar.bullets:if bullet.canDelete or bullet.outOfBounds():GameVar.bullets.remove(bullet)# 从列表中删除英雄机if GameVar.hero.canDelete == True:GameVar.heroes -= 1if GameVar.heroes == 0:#easygui.msgbox('游戏结束')GameVar.state = GameVar.STATES['GAME_OVER']else:GameVar.hero = Hero(0, 0, 60, 75, 1, h)# 定义GameVar类class GameVar():sky = Sky()enemies = []# 产⽣敌飞机的时间间隔lastTime = 0interval = 1.5# 重绘飞⾏物的时间间隔paintLastTime = 0paintInterval = 0.04# 创建英雄机对象hero = Hero(0, 0, 60, 75, 1, h)# 创建列表存储⼦弹对象bullets = []# 添加分数和⽣命值score = 0heroes = 3#创建字典存储游戏状态STATES = {'START':1,'RUNNING':2,'PAUSE':3,'GAME_OVER':4}state = STATES['START']print(GameVar.state)# 定义renderText⽅法def renderText(text, position):my_font = pygame.font.SysFont("微软雅⿊", 40)newText = my_font.render(text, True, (255, 255, 255))canvas.blit(newText, position)# 创建游戏退出事件处理⽅法def handleEvent():for event in pygame.event.get():if event.type == pygame.QUIT or event.type == KEYDOWN and event.key == K_ESCAPE: pygame.quit()sys.exit()#点击⿏标开始游戏if event.type == MOUSEBUTTONDOWN and event.button == 1:if GameVar.state == GameVar.STATES['START']:GameVar.state = GameVar.STATES['RUNNING']# 英雄机跟随⿏标移动if event.type == MOUSEMOTION:if GameVar.state == GameVar.STATES['RUNNING']:GameVar.hero.x = event.pos[0] - GameVar.hero.width / 2GameVar.hero.x = event.pos[0] - GameVar.hero.width / 2 GameVar.hero.y = event.pos[1] - GameVar.hero.height / 2# 调⽤⽅法判断⿏标移⼊画布if isMouseOver(event.pos[0], event.pos[1]):#print('⿏标移⼊事件')if GameVar.state == GameVar.STATES['PAUSE']:GameVar.state = GameVar.STATES['RUNNING']# 调⽤⽅法判断⿏标移出画布if isMouseOut(event.pos[0], event.pos[1]):#print('⿏标移出事件')if GameVar.state == GameVar.STATES['RUNNING']:GameVar.state = GameVar.STATES['PAUSE']# 创建⽅法判断⿏标移出画布def isMouseOut(x, y):if x >= 479 or x <= 0 or y >= 649 or y <= 0:return Trueelse:return False# 创建⽅法判断⿏标移⼊画布def isMouseOver(x, y):if x > 1 and x < 479 and y > 1 and y < 649:return Trueelse:return False# 创建checkHit⽅法def checkHit():# 判断英雄机是否与每⼀架敌飞机发⽣碰撞for enemy in GameVar.enemies:if GameVar.hero.hit(enemy):# 敌机和英雄机调⽤bang⽅法enemy.bang(1)GameVar.hero.bang(2)# 判断每⼀架敌飞机是否与每⼀颗⼦弹发⽣碰撞for bullet in GameVar.bullets:if enemy.hit(bullet):# 敌机和⼦弹调⽤bang⽅法enemy.bang(0)bullet.bang(0)#创建controlState⽅法控制游戏状态def controlState():#游戏开始状态if GameVar.state == GameVar.STATES['START']:GameVar.sky.paint()GameVar.sky.step()canvas.blit(logo,(-40,200))canvas.blit(startgame,(150,400))#游戏运⾏状态elif GameVar.state == GameVar.STATES['RUNNING']:componentEnter()componentPaint()componentStep()checkHit()GameVar.hero.shoot()componentDelete()#游戏暂停状态elif GameVar.state == GameVar.STATES['PAUSE']:componentPaint()componentPaint()GameVar.sky.step()canvas.blit(pause,(0,0))#游戏结束状态elif GameVar.state == GameVar.STATES['GAME_OVER']: componentPaint()GameVar.sky.step()renderText('gameOver',(180,320))while True:#调⽤控制游戏状态的⽅法controlState()# 刷新屏幕pygame.display.update()# 调⽤handleEvent⽅法handleEvent()# 延迟处理pygame.time.delay(15)运⾏程序就可以了!。

Python游戏设计案例实战第9章 游戏实战篇——人机对战井字棋游戏

Python游戏设计案例实战第9章  游戏实战篇——人机对战井字棋游戏

def main():
computer, human = pieces()
turn = X
board = new_board()
display_board(board)
while not winner(board):
#当返回False继续,否则结束循环
if turn == human:
move = human_move(board, human)
(2)否则,如果有一步棋可以让玩家在本轮获胜,就选那一步走。
(3)否则,电脑机器人应该选择最佳空位置来走。最佳位置就是中间 那个,第二好位置是四个角,剩下的就都算第三好的了。
9.3 对战井字棋游戏设计步骤
1.确定谁先走
#询问玩家你是否先走 def ask_yes_no(question):
response = None while response not in ("y", "n"): #如果输入不是"y", "n",继续重新输入
print("\n玩家你先走.") human = X computer = O else: print("\n电脑先走.") computer = X human = O return computer, human
9.3 对战井字棋游戏设计步骤
2.产生新的保存走棋信息列表和显示棋盘
#产生保存走棋信息列表board def new_board():
board[move] = computer if winner(board) == computer:
print("电脑下棋位置..." ,move) return move # 取消走棋方案 board[move] = EMPTY

基于Python的飞机大战游戏开发

基于Python的飞机大战游戏开发

基于Python的飞机大战游戏开发基于Python的飞机大战游戏开发引言飞机大战游戏自问世以来,一直受到广大玩家的喜爱。

随着计算机技术的不断发展和普及,基于Python的飞机大战游戏开发也成为了一项具有挑战性和创新性的任务。

本文将介绍基于Python的飞机大战游戏开发过程中的关键步骤和技术,以及其中涉及的基于Python编程语言的特点和优势。

一、飞机大战游戏概述飞机大战游戏是一种射击游戏,玩家需要操控一个战斗飞机,与敌机进行空中对抗。

通过射击敌机并躲避敌机的攻击,玩家可以获得积分和能力提升道具,逐渐完成游戏目标。

二、Python编程语言简介Python是一种高级编程语言,被广泛应用于各种领域。

它具有简洁而优雅的语法,易学易用的特点,适合初学者入门。

此外,Python还具有丰富的第三方库和强大的生态系统,为开发飞机大战游戏提供了良好的基础。

三、游戏开发前期准备在进行游戏开发之前,我们需要对游戏进行详细的需求分析和规划。

主要包括:1.确定游戏的基本功能和玩法,例如玩家的控制方式、敌机的种类和行为等。

2.设计游戏的界面和图形风格,选择合适的美术资源。

3.搭建游戏开发环境,确保Python及相关开发库的安装和配置完成。

四、游戏主要功能实现1.游戏主循环游戏主循环是游戏的核心部分,它负责监听用户的输入和更新游戏的状态。

在这个循环中,我们需要实现游戏界面的绘制、用户输入的响应以及游戏逻辑的计算等功能。

2.玩家飞机玩家飞机是游戏中最基本的角色之一,玩家将通过操控飞机进行战斗。

我们可以利用Python的图形库来实现玩家飞机的绘制和移动控制。

同时,还可以设计不同类型的子弹和加速道具等来提升飞机的战斗能力。

3.敌机敌机是游戏中的主要敌人,玩家需要通过射击和躲避来与敌机进行战斗。

我们可以设计多种类型的敌机,每种敌机具有不同的行为和攻击方式。

在敌机的移动和攻击过程中,我们可以利用Python的物理引擎库来实现更加真实的效果。

Python游戏设计案例实战第9章 游戏实战篇——人机对战井字棋游戏

Python游戏设计案例实战第9章  游戏实战篇——人机对战井字棋游戏

9.3 对战井字棋游戏设计步骤
3.产生可以合法走棋位置序列 #产生可以合法走棋位置序列(也就是还未下过子位置) def legal_moves(board):
moves = [] for square in range(9):
if board[square] == EMPTY: moves.append(square)
print("\n玩家你先走.") human = X computer = O else: print("\n电脑先走.") computer = X human = O return computer, human
9.3 对战井字棋游戏设计步骤
2.产生新的保存走棋信息列表和显示棋盘
#产生保存走棋信息列表board def new_board():
if board[i]==EMPTY: board2[i]=i
print("\t", board2[0], "|", board2[1], "|", board2[2]) print("\t", "---------") print("\t", board2[3], "|", board2[4], "|", board2[5]) print("\t", "---------") print("\t", board2[6], "|", board2[7], "|", board2[8], "\n")
return moves
9.3 对战井字棋游戏设计步骤

Python代码的人机大战(循环嵌套)

Python代码的人机大战(循环嵌套)

Python代码的⼈机⼤战(循环嵌套)第⼀次动⼿写随笔,记录⼀下今早的1.5⼩时努⼒成果题⽬是这样的: ⼈和机器进⾏猜拳游戏写成⼀个类,⾸先选择⾓⾊:1 曹操 2张飞 3 刘备,然后选择的⾓⾊进⾏猜拳:1剪⼑ 2⽯头 3布玩家输⼊⼀个1-3的数字;然后电脑出拳随机产⽣1个1-3的数字,提⽰电脑出拳结果( 1剪⼑ 2⽯头 3布),双⽅出拳完毕后:⾓⾊和机器出拳对战,对战结束后,最后出⽰本局对战结果...赢...输,然后提⽰⽤户是否继续?按y继续,按n退出。

最后结束的时候输出结果⾓⾊赢⼏局电脑赢⼏局,平局⼏次游戏结束。

代码如下:import randomclass game_huaquan():def Gamer(self):Part = int(input("请选择你要操作的⾓⾊,1.曹操 2.张飞 3.刘备:"))print('你选择的⾓⾊是:{}'.format(parts[Part]))return Partdef Game(self,win=0,lose=0,draw=0):s = ('1', '2', '3')S = ("","剪⼑", "⽯头", "布")while True:input_number = input("请输⼊出拳结果,1.剪⼑ 2.⽯头 3.布\n")random_number = random.randint(1, 3)Random = S[random_number]if input_number not in s:print('输⼊有误,请重新输⼊')continueelse:input_number = int(input_number)Input = S[input_number]while True:if input_number == random_number:print('您出拳结果:{}\n电脑出拳结果:{} \n打平'.format(Input,Random))draw += 1if (input_number == 1 and random_number== 2) or (input_number==2 and random_number== 3) or (input_number==3 and random_number== 1):print('您出拳结果:{} \n电脑出拳结果:{} \n您输了'.format(Input,Random))lose += 1if (input_number == 2 and random_number == 1) or (input_number == 3 and random_number== 2) or (input_number == 1 and random_number == 3):print('您出拳结果:{}\n电脑出拳结果:{} \n您赢了'.format(Input,Random))win += 1while True:con = (input("输⼊'Y'继续游戏,输⼊'N'结束游戏:\n")).upper()if con == 'Y':breakelif con == 'N':return win,lose,drawelse:print("输⼊错误请重新输⼊!")continuebreakdef Game_console(self,Part,win,lose,draw):gamer = parts[Part]print('本次游戏中,您操作的⾓⾊{}赢{}局,输{}局,平{}局,进⾏了{}局'.format(gamer, win, lose, draw, (win+lose+draw)))if __name__ == '__main__':parts = ('曹操', '张飞', '刘备')part = game_huaquan().Gamer()Scene = game_huaquan().Game()game_huaquan().Game_console(part,Scene[0],Scene[1],Scene[2]) 注意要点有4处: 1.出拳情况应该往结果上靠,刚开头⾛错路,写了9个if,实际上3个就能解决了,要么赢、要么输、要么平。

计算机编程编写一个简单的人机对战游戏

计算机编程编写一个简单的人机对战游戏

计算机编程编写一个简单的人机对战游戏编程语言:Python一、简介人机对战游戏是计算机编程中常见的项目之一。

通过编写游戏代码,可以实现人类和计算机之间的对战,增加了游戏的趣味性和挑战性。

本文将介绍如何使用Python语言编写一个简单的人机对战游戏。

二、游戏规则在这个简单的人机对战游戏中,游戏场地为一个矩形区域,玩家和计算机分别控制一个小方块,通过键盘控制方向进行移动。

游戏的目标是在规定时间内尽可能多地吃到食物,同时要避免撞到边界或对方。

当时间结束后,比较两方吃到的食物数量,吃得更多的一方获胜。

三、游戏设计1. 导入必要的模块在Python中,我们可以使用pygame模块来实现简单的游戏功能。

首先,我们需要导入pygame模块并初始化:```pythonimport pygameimport randompygame.init()```2. 设定游戏界面设置游戏界面的宽度和高度,以及游戏界面的标题:```pythonwidth = 800height = 600screen = pygame.display.set_mode((width, height))pygame.display.set_caption("人机对战游戏")```3. 定义玩家和计算机的方块通过定义一个方块类,我们可以创建出玩家和计算机的方块对象,并设置初始位置和移动速度:```pythonclass Block(pygame.sprite.Sprite):def __init__(self, x, y, color):super().__init__()self.image = pygame.Surface([20, 20])self.image.fill(color)self.rect = self.image.get_rect()self.rect.x = xself.rect.y = yself.speed_x = 0self.speed_y = 0def update(self):self.rect.x += self.speed_xself.rect.y += self.speed_y```4. 定义食物通过创建食物对象,我们可以随机生成食物的位置,并在游戏界面上显示出来:```pythonclass Food(pygame.sprite.Sprite):def __init__(self, color):super().__init__()self.image = pygame.Surface([20, 20])self.image.fill(color)self.rect = self.image.get_rect()def reset(self):self.rect.x = random.randrange(0, width - 20)self.rect.y = random.randrange(0, height - 20)```5. 实现游戏逻辑通过控制玩家方块的移动,判断是否吃到食物或撞到边界或对方,来更新游戏的状态。

基于Python的飞机大战游戏开发

基于Python的飞机大战游戏开发

基于Python的飞机大战游戏开发基于Python的飞机大战游戏开发一、游戏开发背景随着互联网的普及和技术的不断进步,游戏开发行业也持续蓬勃发展。

飞机大战游戏作为一种经典的射击游戏类型,在游戏玩家中依然很受欢迎。

本文将基于Python编程语言,介绍如何开发一款简单的飞机大战游戏。

通过本次开发,读者可以了解到游戏开发的基本流程和技术点,也可以在此基础上进行更复杂的游戏开发。

二、游戏开发流程1. 游戏概念设定:在游戏开发之前,首先需要对游戏的概念进行设定。

比如,本游戏是一款经典的2D飞机大战游戏,玩家控制一个飞机进行射击击败敌人、拾取道具等游戏操作。

设定游戏的主题和目标,这样可以更好地引导游戏的开发进程。

2. 游戏界面设计:游戏界面是玩家和游戏交互的重要环节。

在这一步中,我们需要设计游戏的背景、角色、道具等元素,以及各种界面效果,比如游戏开始、暂停、结束等。

Python的Pygame库提供了丰富的图形库和工具,可以帮助我们实现这些设计。

3. 游戏逻辑编码:在游戏逻辑编码阶段,我们需要根据游戏的规则和设定,编写游戏的各种功能和行为。

比如,玩家飞机的移动、射击,敌人的生成和移动,道具的产生和效果等。

可以通过Python语言的条件判断、循环等程序结构,实现游戏的逻辑功能。

4. 游戏测试和调试:在整个开发过程中,我们需要不断地进行测试和调试,确保游戏的各项功能正常运行。

这里可以先从单一功能进行测试,再逐渐整合各个模块进行整体测试。

通过测试和调试,可以及时发现和解决游戏中的bug和问题,提高游戏的质量和稳定性。

5. 游戏优化和美化:在游戏开发的最后阶段,我们需要对游戏进行优化和美化,使其更加流畅、漂亮和具有吸引力。

优化方面可以从游戏性能、代码的简洁性等方面考虑,优化游戏的加载速度和运行效率;美化方面可以加入一些音效、背景音乐,还可以通过更加精美的图形、动画效果等,提升游戏的表现力和用户体验。

三、Python的游戏开发库在Python的游戏开发中,Pygame库是非常流行的开发工具。

Python实现五子棋联机对战小游戏

Python实现五子棋联机对战小游戏

Python实现五⼦棋联机对战⼩游戏⽬录效果演⽰开发⼯具环境搭建主要代码修改的地⽅效果演⽰开发⼯具Python版本: 3.6.4相关模块:pygame模块;PyQt5模块;以及⼀些Python⾃带的模块。

环境搭建安装Python并添加到环境变量,pip安装需要的相关模块即可。

主要代码这⾥简单介绍下原理吧,代码主要⽤PyQt5写的,pygame只⽤来播放⼀些⾳效。

⾸先,设计并实现个游戏主界⾯:代码实现如下123 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24'''游戏开始界⾯'''class gameStartUI(QWidget):def__init__(self, parent=None, **kwargs):super(gameStartUI, self).__init__(parent)self.setFixedSize(760, 650)self.setWindowTitle('五⼦棋- : ilove-python')self.setWindowIcon(QIcon(cfg.ICON_FILEPATH))# 背景图⽚palette =QPalette()palette.setBrush(self.backgroundRole(), QBrush(QPixmap(cfg.BACKGROUND_IMAGEPATHS.get('bg_start')))) self.setPalette(palette)# 按钮# --⼈机对战self.ai_button =PushButton(cfg.BUTTON_IMAGEPATHS.get('ai'), self)self.ai_button.move(250, 200)self.ai_button.show()self.ai_button.click_signal.connect(self.playWithAI)# --联机对战self.online_button =PushButton(cfg.BUTTON_IMAGEPATHS.get('online'), self)self.online_button.move(250, 350)self.online_button.show()self.online_button.click_signal.connect(self.playOnline)'''⼈机对战'''def playWithAI(self):self.close()252627282930313233self.gaming_ui = playWithAIUI(cfg)self.gaming_ui.exit_signal.connect(lambda: sys.exit())self.gaming_ui.back_signal.connect(self.show) self.gaming_ui.show() '''联机对战''' def playOnline(self): self.close()self.gaming_ui = playOnlineUI(cfg, self)self.gaming_ui.show()会pyqt5的应该都可以写出这样的界⾯,没啥特别的,记得把⼈机对战和联机对战两个按钮触发后的信号分别绑定到⼈机对战和联机对战的函数上就⾏。

python 例程

python 例程

python 例程【python 例程】编写一个简单的人机对战游戏在本篇文章中,我们将使用Python 编程语言来创建一个简单的人机对战游戏。

这个游戏将基于控制台进行输入和输出,并且通过利用条件语句、循环和随机数生成器等Python 的核心特性来实现。

首先,我们需要定义游戏的规则和目标。

在这个游戏中,玩家和电脑将分别选择“剪刀”、“石头”或“布”中的一种来进行猜拳。

根据猜拳的规则,剪刀可以打败布,布可以打败石头,而石头可以打败剪刀。

我们的目标是编写一段能够模拟这个游戏规则的程序,并且通过对玩家和电脑的选择进行比较,来决定游戏的结果。

接下来,我们需要导入一些Python 的模块来帮助我们完成这个任务。

我们将使用`random` 模块来生成电脑的选择,以及使用`time` 模块来引入一些时间延迟,以便使游戏流程更为逼真。

我们可以添加以下代码来导入这两个模块:pythonimport randomimport time然后,我们需要定义一些变量来存储游戏需要的数据。

对于玩家和电脑的选择,我们可以使用一个字符串来表示。

对于游戏的结果,我们可以使用一个整数来表示,其中1 表示玩家胜利,0 表示平局,-1 表示电脑胜利。

我们可以添加以下代码来定义这些变量:pythonplayer_choice = ""computer_choice = ""result = 0现在,我们可以开始编写游戏的主要逻辑。

首先,我们需要提示玩家做出选择,并且等待玩家输入。

我们可以添加以下代码来完成这一步骤:pythonprint("剪刀、石头、布游戏开始!")print("请选择剪刀、石头或布:")player_choice = input()接下来,我们需要生成电脑的选择。

我们可以使用`random` 模块中的`choice()` 函数来随机选择一个字符串。

Python实现的人机对战小游戏

Python实现的人机对战小游戏

Python实现的人机对战小游戏
——<石头、 剪刀、布>
各版本程序功能描述
版本1.0 获取双方对战人员名单 版本2.0实现一次对战 版本3.0根据对战结果评输赢 版本4.0实现多次对战 版本5.0实现最终结果的评判
项目分解-1.0版获取双方对战人员名单
涉及知识点:
(1)print()向控制台输出信息 (2)input()从键盘录入信息,结果为str类型 (3)控制台文本样式
( per_fist==2 and com_fist==3) or
(per_fist==3 and com_fist==1):
print(‘玩家赢’)
(3)电脑赢 其它情况
else:
print(‘电脑赢’)
项目分解-版本3.0根据对战结果评输赢
项目分解-版本4.0实现多次对战
while循环循环语法结构源自玩家2 电脑2玩家3 电脑3
玩家的出拳数值与电脑的出拳数值相等
代码逻辑: if per_fist==com_fist :
print(‘平局’)
(2)玩家赢
思维逻辑: 石头 VS 剪刀 or 剪刀VS 布
or 布 VS 石头
玩家1 电脑2
玩家2 电脑3
玩家3 电脑1
代码逻辑: elif ( per_fist==1 and com_fist==2) or
(1)初始化变量 answer=input(‘Are you ready?’)
(2)条件判断 while answer==‘y’: (3)循环操作评判输赢 ...... (4)改变变量 answer=input(‘继续吗?’)
项目分解-版本5.0实现最终结果的评判
解决思路
(1)声明两个变量分别用于存储玩家和电脑的对 战积分

【pygame】Python制作五子棋人机对战

【pygame】Python制作五子棋人机对战

【pygame】Python制作五⼦棋⼈机对战本⽂代码基于 python3.6 和 pygame1.9.4。

五⼦棋⽐起我之前写的⼏款游戏来说,难度提⾼了不少。

如果是⼈与⼈对战,那么,电脑只需要判断是否赢了就可以。

如果是⼈机对战,那你还得让电脑知道怎么下。

我们先从简单的问题来看。

画棋盘⾸先肯定是要画出棋盘来,⽤ pygame 画出⼀个 19 × 19 或 15 × 15 的棋盘并不是什么难事,这在之前的⽂章中已经多次⽤到,就不赘述了。

画棋⼦需要说⼀下的是画棋⼦,因为没找到什么合适的棋⼦图⽚,所以只要⾃⼰来画棋⼦。

我们⽤ pygame.draw.circle 画出来的圆形是这样的:锯齿状⼗分明显,pygame.draw 中有画抗锯齿直线的函数 aaline,但是并没有 aacircle 这样的函数来画⼀个抗锯齿的圆。

这⾥就需要⽤到 pygame.gfxdraw 啦。

pygame.gfxdraw ⽬前还仅是实验版本,这意味着这个 API 可能会在以后的 pygame 版本中发⽣变化或消失。

要绘制抗锯齿和填充形状,请⾸先使⽤函数的aa *版本,然后使⽤填充版本。

例如:col = (255, 0, 0)surf.fill((255, 255, 255))pygame.gfxdraw.aacircle(surf, x, y, 30, col)pygame.gfxdraw.filled_circle(surf, x, y, 30, col)我们⽤这个⽅法在棋盘上画⼀个棋⼦试试看。

可以看到效果已明显改善。

落⼦落⼦需要判断⿏标事件,当⿏标左键点击,获取⿏标点击的位置,然后根据棋盘的位置,计算出棋⼦落在棋盘的位置。

while True:for event in pygame.event.get():if event.type == QUIT:sys.exit()elif event.type == MOUSEBUTTONDOWN:pressed_array = pygame.mouse.get_pressed()if pressed_array[0]: # ⿏标左键点击mouse_pos = pygame.mouse.get_pos()click_point = _get_clickpoint(mouse_pos)当⼀⼦落下,如何判定是否胜利?可以肯定的是,当某⼀⼦落下的时候,如果出现了 5 连,那么落下的这颗⼦必定在这条 5 连线上。

python实现人机五子棋

python实现人机五子棋

python实现⼈机五⼦棋本⽂实例为⼤家分享了python实现⼈机五⼦棋的具体代码,供⼤家参考,具体内容如下图形界⾯引⽤PyQt5,还有socket通信。

可以局域⽹对战,可以⼈机对战,应该存在⼀些⼩的bug,但是还没有找出来。

希望读者可以找到下⾯附⼏张运⾏的截图:五⼦棋.py代码:from PyQt5.QtWidgets import *from PyQt5.QtGui import *import sysimport MyButtonimport DoublePlayerGameimport SinglePlayerGamefrom NetConfig import *import NetPlayerGameclass Mainwindow(QWidget):def __init__(self,parent = None):super().__init__(parent)self.resize(760,650)self.setWindowTitle("我的五⼦棋")#设置窗⼝图标self.setWindowIcon(QIcon("source/icon.ico"))#设置背景图⽚p = QPalette(self.palette())#获得当前的调⾊板brush = QBrush(QImage("source/五⼦棋界⾯.png"))p.setBrush(QPalette.Background,brush)#设置调⾊版self.setPalette(p)#给窗⼝设置调⾊板self.singlePlayerBtn = MyButton.MyButton('source/⼈机对战_hover.png', 'source/⼈机对战_normal.png','source/⼈机对战_press.png',parent=self)self.singlePlayerBtn.move(300,300)self.dancelePlayerBtn = MyButton.MyButton('source/双⼈对战_hover.png', 'source/双⼈对战_normal.png','source/双⼈对战_press.png',parent=self)self.dancelePlayerBtn.move(300,400)#self.dancelePlayerBtn.clicked.connect(DoublePlayerGame)self.drawlePlayerBtn = MyButton.MyButton('source/联机对战_hover.png', 'source/联机对战_normal.png','source/联机对战_press.png',parent=self)self.drawlePlayerBtn.move(300,500)#绑定开始双⼈游戏信号和槽函数self.dancelePlayerBtn.clicked.connect(self.startDoubliGame)self.singlePlayerBtn.clicked.connect(self.startSingleGame)self.drawlePlayerBtn.clicked.connect(self.startNetGame)def startDoubliGame(self):print("in")#构建双⼈对战界⾯self.doublePlayerGame = DoublePlayerGame.DoublePlayGame()#绑定返回界⾯self.doublePlayerGame.backSignal.connect(self.showStartGame)self.doublePlayerGame.show()#显⽰游戏界⾯self.close()def startSingleGame(self):self.SingleGame = SinglePlayerGame.SinglePlayerGame()self.SingleGame.backSignal.connect(self.showStartGame2)self.SingleGame.show()self.close()def startNetGame(self):Config = NetConfigWidget()Config.exit_signal.connect(self.show)Config.show()Config.config_signal.connect(self.receiveNetConfig)self.close()def receiveNetConfig(self,nettype,name,ip,port):'''接收⽹络配置信息'''print("net config:",nettype,name,ip,port)if nettype == "client":net_object = NetClient(name,ip,port)elif nettype == "server":net_object = NetServer(name,ip,port)else:returnPlayerGame = PlayerGame(net_object=net_object) PlayerGame.backSignal.connect(self.show)self.close()PlayerGame.show()Config.hide()'''lbl = QLabel(self)pix = QPixmap("source/⼈机⼤战_norma.")'''#显⽰开始界⾯def showStartGame(self):self.show()self.doublePlayerGame.close()def showStartGame2(self):self.show()self.SingleGame.close()if __name__ == "__main__":import cgitbcgitb.enable("text")a = QApplication(sys.argv)m = Mainwindow()m.show()sys.exit(a.exec_())doubleplayergame.py代码:from PyQt5.QtWidgets import *from PyQt5.QtGui import *from PyQt5.QtCore import *from PyQt5 import *import sysclass Chessman(QLabel):def __init__(self, color = "black",parent = None):super().__init__(parent)self.color = colorself.pic = Noneif self.color == "black":self.pic = QPixmap("source/⿊⼦.png")else:self.pic = QPixmap("source/⽩⼦.png")self.setPixmap(self.pic)self.setFixedSize(self.pic.size())#设置棋⼦⼤⼩self.show()self.x = 0self.y = 0def move(self,a0:QtCore.QPoint):super().move(a0.x()-15,a0.y()-15)def setIndex(self,x,y):self.x = xself.y = yimport MyButtonclass DoublePlayGame(QWidget):backSignal = pyqtSignal()#返回信号def __init__(self,parent = None):super().__init__(parent=parent)#左上⾓chessboard[0][0]#右上⾓chessboard[0][18]#左下⾓chessboard[18][0]#右下⾓chessboard[18][18]#chessboard[⾏下标][列下标]self.chessboard = [[None for i in range(19)] for i in range(19)]#落⼦棋⼦颜⾊self.turnChessColor = "black"self.history = []self.history2 = []self.is_over = False#配置背景图p = QPalette(self.palette())#获得当前的调⾊板brush = QBrush(QImage("source/游戏界⾯.png"))p.setBrush(QPalette.Background,brush)#设置调⾊版self.setPalette(p)#给窗⼝设置调⾊板#设置标题#self.resize(760,650)self.setWindowTitle("双⼈联机")#设置窗⼝图标self.setWindowIcon(QIcon("source/icon.ico"))#设置窗⼝⼤⼩self.setFixedSize(QImage("source/游戏界⾯.png").size())self.backBtn = MyButton.MyButton('source/返回按钮_hover.png', 'source/返回按钮_normal.png','source/返回按钮_press.png',parent=self)self.backBtn.move(650,50)self.startBtn = MyButton.MyButton('source/开始按钮_hover.png', 'source/开始按钮_normal.png','source/开始按钮_press.png',parent=self)self.startBtn.move(650,300)self.returnBtn = MyButton.MyButton('source/悔棋按钮_hover.png', 'source/悔棋按钮_normal.png','source/悔棋按钮_press.png',parent=self)self.returnBtn.move(650,400)self.loseBtn = MyButton.MyButton('source/认输按钮_hover.png', 'source/认输按钮_normal.png','source/认输按钮_press.png',parent=self)self.loseBtn.move(650,500)#绑定返回按钮self.backBtn.clicked.connect(self.goBack)self.startBtn.clicked.connect(self.restar)self.loseBtn.clicked.connect(self.lose)self.returnBtn.clicked.connect(self.huiback)self.gameStatu = []self.focusPoint = QLabel(self)self.focusPoint.setPixmap(QPixmap("source/标识.png"))def goBack(self):self.backSignal.emit()self.close()def closeEvent(self, a0: QtGui.QCloseEvent):self.backSignal.emit()def mouseReleaseEvent(self, a0: QtGui.QMouseEvent):if self.gameStatu == False:return Noneprint(a0.pos())print("x:",a0.x())print("y:",a0.y())pos,chess_index = self.reversePos(a0)if pos is None:returnif self.chessboard[chess_index[1]][chess_index[0]] != None:returnself.chess = Chessman(color=self.turnChessColor,parent=self)self.chess.setIndex(chess_index[0], chess_index[1])self.chess.move(pos)self.chess.show()#显⽰棋⼦self.history.append(self.chess)self.history2.append(self.focusPoint)self.focusPoint.move(QPoint(pos.x()-15,pos.y()-15))self.focusPoint.show()self.focusPoint.raise_()print("棋盘交点位置:",chess_index)#放⼊棋盘self.chessboard[chess_index[1]][chess_index[0]] = self.chessif self.turnChessColor=="black":self.turnChessColor="white"else:self.turnChessColor="black"self.lbl = Noneresult = self.isWin(self.chess)if result != None:print(result + '赢了')self.showResult(result)#⾃动落⼦#self.autoDown()#坐标转换def reversePos(self, a0: QtCore.QPoint):if a0.x() <= 50 - 15 or a0.x() >= 590 +15 or a0.y() <= 50 - 15 or a0.y() >= 590+15 : return None, Noneself.x = (a0.x()-35)//30self.y = (a0.y()-35)//30x = 50+30*self.xy = 50+30*self.yreturn QPoint(x, y),(self.x, self.y)def isWin(self,chessman):print("in iswin,lastChessman:",chessman.color,chessman.x,chessman.y)#⽔平⽅向y相同,chessboard[chessman.y][i]count = 1#左边i = chessman.x - 1while i>=0:if self.chessboard[chessman.y][i] == None or self.chessboard[chessman.y][i].color != chessman.color: breakcount += 1i -= 1#右边i = chessman.x + 1while i<=18:if self.chessboard[chessman.y][i] == None or self.chessboard[chessman.y][i].color != chessman.color: breakcount += 1i += 1if count >=5:return chessman.colorcount = 1j = chessman.y - 1while j >= 0:if self.chessboard[j][chessman.x] == None or self.chessboard[j][chessman.x].color != chessman.color: breakcount += 1j -= 1j = chessman.y + 1while j <= 18:if self.chessboard[j][chessman.x] == None or self.chessboard[j][chessman.x].color != chessman.color: breakcount += 1j += 1if count >=5:return chessman.colorcount = 1j,i = chessman.y - 1,chessman.x + 1while j >= 0 and i <= 18:if self.chessboard[j][i] == None or self.chessboard[j][i].color != chessman.color:breakcount += 1j -= 1i += 1j,i = chessman.y + 1,chessman.x - 1while i >= 0 and j <= 18:if self.chessboard[j][i] == None or self.chessboard[j][i].color != chessman.color:breakcount += 1i -= 1j += 1if count >=5:return chessman.colorcount = 1j,i = chessman.y-1,chessman.x-1while j>=0 and i>=0:if self.chessboard[j][i] == None or self.chessboard[j][i].color != chessman.color:breakcount += 1j -= 1i -= 1j,i = chessman.y+1,chessman.x+1while j<=18 and i<=18:if self.chessboard[j][i] == None or self.chessboard[j][i].color != chessman.color:breakcount += 1j += 1i += 1if count >=5:return chessman.colorreturn Nonedef showResult(self,isWin = None):self.gameStatu = Falseif isWin == "white":self.lbl = QLabel(self)self.lbl.setPixmap(QPixmap("source/⽩棋胜利.png")) self.lbl.move(150,150)self.lbl.show()elif isWin == "black":self.lbl = QLabel(self)self.lbl.setPixmap(QPixmap("source/⿊棋胜利.png")) self.lbl.move(150,150)self.lbl.show()else:returndef restar(self):for i in range(19):for j in range(19):if self.chessboard[i][j] != None:self.chessboard[i][j].close()self.chessboard[i][j] = Noneself.focusPoint.close()else:passif self.lbl != None:self.lbl.close()self.gameStatu = Truedef lose(self):if self.gameStatu == False:returnif self.turnChessColor == "black":self.lbl = QLabel(self)self.lbl.setPixmap(QPixmap("source/⽩棋胜利.png")) self.lbl.move(150,150)self.lbl.show()elif self.turnChessColor == "white":self.lbl = QLabel(self)self.lbl.setPixmap(QPixmap("source/⿊棋胜利.png")) self.lbl.move(150,150)self.lbl.show()else:returndef huiback(self):if self.gameStatu == False:returnm = self.history.pop()a = self.history2.pop()self.chessboard[m.y][m.x] = Nonem.close()a.close()if self.turnChessColor=="black":self.turnChessColor="white"else:self.turnChessColor="black"if __name__ == "__main__":import cgitbcgitb.enable("text")a = QApplication(sys.argv)m = DoublePlayGame()m.show()sys.exit(a.exec_())passNetConfig.py代码:from PyQt5.QtWidgets import *from PyQt5.QtCore import *from PyQt5 import *import socketimport threadingclass NetConfigWidget(QWidget):config_signal = pyqtSignal([str,str,str,str])exit_signal = pyqtSignal()def __init__(self,parent = None):super().__init__(parent = parent)self.initUI()def initUI(self):self.setWindowTitle("⽹络配置")_label = QLabel("姓名:",self)_input = QLineEdit("玩家1",self)self.ip_label = QLabel("IP:",self)self.ip_input = QLineEdit("127.0.0.1",self)self.port_label = QLabel("Prot:",self)self.port_input = QLineEdit("10086",self)self.client_button = QPushButton("链接主机",self)self.server_button = QPushButton("我是主机",self)gridLayout = QGridLayout()gridLayout.addWidget(_label,0,0)gridLayout.addWidget(_input,0,1)gridLayout.addWidget(self.ip_label,1,0)gridLayout.addWidget(self.ip_input,1,1)gridLayout.addWidget(self.port_label,2,0)gridLayout.addWidget(self.port_input,2,1)gridLayout.addWidget(self.client_button,3,0)gridLayout.addWidget(self.server_button,3,1)self.setLayout(gridLayout)self.client_button.clicked.connect(self.client_btn_signal)self.server_button.clicked.connect(self.server_btn_signal)def server_btn_signal(self):self.config_signal.emit("server",_input.text(),self.ip_input.text(),self.port_input.text()) def client_btn_signal(self):self.config_signal.emit("client",_input.text(),self.ip_input.text(),self.port_input.text()) def closeEvent(self,a0:QtGui.QCloseEvent):self.close()self.exit_signal.emit()class NetClient(QObject):msg_signal = pyqtSignal([str])def __init__(self,name,ip,port):super().__init__() = nameself.ip = ipself.port = portself.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)def buildConnect(self):'''建⽴链接'''self.socket.connect((self.ip,int(self.port)))threading.Thread(target=self.recv).start()passdef send(self,data):'''发送数据data(发送的数据)字符串类型'''self.socket.send(data.encode())passdef recv(self):'''接收数据'''while True:try:data = self.socket.recv(4096).decode()self.msg_signal.emit(data)except:passclass NetServer(QObject):msg_signal = pyqtSignal([str])def __init__(self,name,ip,port):super().__init__() = nameself.ip = ipself.port = portself.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.cli_socket = Nonedef buildConnect(self):self.socket.bind(("",int(self.port)))self.socket.listen(1)threading.Thread(target=self.__acceptConnect).start()def __acceptConnect(self):try:self.cli_socket,cli_addr = self.socket.accept()except:passwhile True:try:data = self.cli_socket.recv(4096).decode()self.msg_signal.emit(data)except Exception as e:print(e)def send(self,data):if self.cli_socket == None:returnself.cli_socket.send(data.encode())if __name__ == "__main__":import sysimport cgitbcgitb.enable("text")a = QApplication(sys.argv)m = NetConfigWidget()m.show()sys.exit(a.exec_())passNetplayerGame.py代码:from DoublePlayerGame import *import jsonfrom NetConfig import *from PyQt5.QtMultimedia import QSoundclass NetPlayerGame(DoublePlayGame):def __init__(self,net_object, parent = None):super().__init__(parent = parent)_object = net_object_object.buildConnect()#建⽴⽹络链接_object.msg_signal.connect(self.parseData)self.m_color = None#玩家棋⼦颜⾊self.cuicuBtn = MyButton.MyButton('source/催促按钮_hover.png','source/催促按钮_normal.png','source/催促按钮_press.png',parent=self)self.cuicuBtn.move(650,600)self.cuicuBtn.clicked.connect(self.cuicu)def cuicu(self):QSound.play('source/cuicu.wav')msg = {}msg['msg_type'] = 'cuicu'_object.send(json.dumps(msg))passdef goBack(self):self.backSignal.emit()self.close()_object.socket.close()def downChessman(self,point,color):'''⾃动落⼦:return:'''#point = self.getPoint()# 注意:x,y坐标对应chess_index = (point.y(), point.x()) # 棋⼦在棋盘中的下标pos = QPoint(50+point.x()*30, 50+point.y()*30) # 棋⼦在棋盘中的坐标self.chessman = Chessman(color=color, parent=self)self.chessman.setIndex(chess_index[0], chess_index[1])self.chessman.move(pos)self.chessman.show() # 显⽰棋⼦# 显⽰标识self.focusPoint.move(QPoint(pos.x() - 15, pos.y() - 15))self.focusPoint.show()self.focusPoint.raise_()self.chessboard[chess_index[0]][chess_index[1]] = self.chessman# 历史记录self.history.append((chess_index[0], chess_index[1], self.chessman.color))# 改变落⼦颜⾊if self.turnChessColor == 'black':self.turnChessColor = 'white'else:self.turnChessColor = 'black'# 判断输赢result = self.isWin(self.chessman)if result != None:print(result + '赢了')self.showResult(result)pass'''{"msg_type":"positon","x":"10","y":"15","color":"black"}'''#解析⽹路数据def parseData(self,data):print("pardata:",data)try:msg = json.loads(data)except Exception as e:print(e)#msg = json.loads(data)print("msg:",msg)if msg["msg_type"] == "position":self.downChessman(QPoint(int(msg["x"]),int(msg["y"])),msg["color"])passelif msg["msg_type"] == "restart":result = rmation(None,'五⼦棋_提⽰消息','请求开始游戏',QMessageBox.Yes |QMessageBox.No) if result == QMessageBox.Yes:self.restartGame()#⽩⼦self.m_color = 'white'msg = {}msg['msg_type'] = "response"msg['action_type'] = 'restart'msg['action_result'] = 'yes'_object.send(json.dumps(msg))else:msg = {}msg['msg_type'] = "response"msg['action_type'] = 'restart'msg['action_result'] = 'no'_object.send(json.dumps(msg))elif msg['msg_type'] == 'response':if msg['action_type'] == 'restart':if msg['action_result'] == 'yes':self.restartGame()self.m_color = 'balck'else:rmation(self,'五⼦棋_提⽰消息','对⽅拒绝游戏')elif msg['action_type'] == 'huiqi':if msg['action_result'] == 'Yes':self.huiqigame()else:rmation(self,'五⼦棋_提⽰消息','对⽅拒绝悔棋',QMessageBox.Yes |QMessageBox.No)elif msg['msg_type'] == 'huiqi':result = rmation(self,'五⼦棋_提⽰消息','对⽅请求悔棋',QMessageBox.Yes |QMessageBox.No) if result == QMessageBox.Yes:msg = {}msg['msg_type'] = "response"msg['action_type'] = 'huiqi'msg['action_result'] = 'Yes'_object.send(json.dumps(msg))self.huiqigame()else:msg = {}msg['msg_type'] = "response"msg['action_type'] = 'huiqi'msg['action_result'] = 'No'_object.send(json.dumps(msg))elif msg['msg_type'] == 'lose':show.showResult(self.m_color)elif msg['msg_type'] == 'cuicu':QSound.play('source/cuicu.wav')QMessageBox.window(self,'0')def restartGame(self):for i in range(19):for j in range(19):if self.chessboard[i][j] != None:self.chessboard[i][j].close()self.chessboard[i][j] = Noneself.focusPoint.close()else:passself.lbl = Noneif self.lbl != None:self.lbl.close()self.gameStatu = Trueself.focusPoint.hide()self.turnChessColor="black"def mouseReleaseEvent(self, a0: QtGui.QMouseEvent):if self.m_color != self.turnChessColor:returnif self.gameStatu == False:return Nonepos,chess_index = self.reversePos(a0)if pos is None:returnif self.chessboard[chess_index[1]][chess_index[0]] != None:returnself.chess = Chessman(color=self.turnChessColor,parent=self)self.chess.setIndex(chess_index[1], chess_index[0])self.chess.move(pos)self.chess.show()#显⽰棋⼦self.history.append(self.chess)self.history2.append(self.focusPoint)self.focusPoint.show()self.focusPoint.raise_()print("棋盘交点位置:",chess_index)#放⼊棋盘self.chessboard[chess_index[1]][chess_index[0]] = self.chess#发送落⼦信息msg = {}msg["msg_type"] = "position"msg["x"] = chess_index[1]msg["y"] = chess_index[0]msg["color"] = self.turnChessColor_object.send(json.dumps(msg))if self.turnChessColor=="black":self.turnChessColor="white"else:self.turnChessColor="black"self.lbl = Noneresult = self.isWin(self.chess)if result != None:print(result + '赢了')self.showResult(result)def huiqi(self):if self.gameStatu == None:QMessageBox.warning(self,'五⼦棋提⽰','游戏没有开始,不能悔棋') if self.m_color != self.turnChessColor:QMessageBox.warning(self,'五⼦棋提⽰','不是你的回合')msg = {}msg['msg_type'] = 'huiqi'_object.send(json.dumps(msg))def huiqigame(self):if self.gameStatu == False:returnm = self.history.pop()a = self.history2.pop()self.chessboard[m.y][m.x] = Nonem.close()a.close()if self.turnChessColor=="black":self.turnChessColor="white"else:self.turnChessColor="black"def restar(self):msg = {}msg["msg_type"] = "restart"_object.send(json.dumps(msg))def lose(self):if self.gameStatu == False:QMessageBox.warning(None,'五⼦棋','游戏没有开始')if self.m_color == "black":self.lbl = QLabel(self)self.lbl.setPixmap(QPixmap("source/⽩棋胜利.png"))self.lbl.move(150,150)self.lbl.show()elif self.m_color == "white":self.lbl = QLabel(self)self.lbl.setPixmap(QPixmap("source/⿊棋胜利.png"))self.lbl.move(150,150)self.lbl.show()else:returnmsg = {}msg['msg_type'] = "lose"#msg['action_type'] = 'restart'#msg['action_result'] = 'no'if __name__ == '__main__':import cgitbcgitb.enable("text")a = QApplication(sys.argv)m = NetPlayerGame()m.show()sys.exit(a.exec_())passMyButton.py代码:# -*- coding:utf-8 -*-# @author: alex# @time: 2018/12/27 16:29from PyQt5 import QtGui, QtCorefrom PyQt5.QtWidgets import *from PyQt5 import *from PyQt5.QtGui import *import sysfrom PyQt5.QtCore import *class MyButton(QLabel):clicked = pyqtSignal()#⾃定义⼀个信号def __init__(self, *args, parent=None):super().__init__(parent)self.hoverPixmap = QPixmap(args[0])self.normalPixmap = QPixmap(args[1])self.pressPixmap = QPixmap(args[2])self.enterState = Falseself.setPixmap(self.normalPixmap)self.setFixedSize(self.normalPixmap.size())def mouseReleaseEvent(self, ev: QtGui.QMouseEvent): if self.enterState == False:self.setPixmap(self.normalPixmap)else:self.setPixmap(self.hoverPixmap)self.clicked.emit()#发射信号print("⿏标释放")passdef mousePressEvent(self, ev: QtGui.QMouseEvent): self.setPixmap(self.pressPixmap)print("⿏标按下")passdef enterEvent(self, a0: QtCore.QEvent):self.setPixmap(self.hoverPixmap)self.enterState = Trueprint("⿏标进⼊")passdef leaveEvent(self, a0: QtCore.QEvent):self.setPixmap(self.normalPixmap)self.enterState = Falseprint("⿏标离开")passif __name__ == '__main__':a = QApplication(sys.argv)mybtn = MyButton('source/⼈机对战_hover.png','source/⼈机对战_normal.png',sys.exit(a.exec_())SingerPlayerGame.py代码:from DoublePlayerGame import *class SinglePlayerGame(DoublePlayGame):def __init__(self, parent=None):super().__init__(parent=parent)self.setWindowTitle('五⼦棋-单机模式')def mouseReleaseEvent(self, a0: QtGui.QMouseEvent):if self.gameStatu == False:return Noneprint(a0.pos())print("x:",a0.x())print("y:",a0.y())pos,chess_index = self.reversePos(a0)if pos is None:returnif self.chessboard[chess_index[1]][chess_index[0]] != None: return# 玩家落⼦super().mouseReleaseEvent(a0)# 电脑落⼦self.autoDown()def getPointScore(self, x, y, color):'''返回每个点的得分y:⾏坐标x:列坐标color:棋⼦颜⾊:return:'''# 分别计算点周围5⼦以内,空⽩、和同⾊的分数blank_score = 0color_score = 0# 记录每个⽅向的棋⼦分数blank_score_plus = [0, 0, 0, 0] # 横向纵向正斜线反斜线 color_score_plus = [0, 0, 0, 0]# 横线# 右侧i = x # 横坐标j = y # 纵坐标while i < 19:if self.chessboard[j][i] is None:blank_score += 1blank_score_plus[0] += 1breakelif self.chessboard[j][i].color == color:color_score += 1color_score_plus[0] += 1else:breakif i >= x + 4:breaki += 1# print('123123')# 左侧i = x # 横坐标j = y # 纵坐标while i >= 0:if self.chessboard[j][i] is None:blank_score += 1blank_score_plus[0] += 1breakelif self.chessboard[j][i].color == color:color_score += 1color_score_plus[0] += 1# 竖线# 上⽅i = x # 横坐标j = y # 纵坐标while j >= 0:if self.chessboard[j][i] is None:blank_score += 1blank_score_plus[1] += 1breakelif self.chessboard[j][i].color == color: color_score += 1color_score_plus[1] += 1else:breakif j <= y - 4:breakj -= 1# 竖线# 下⽅i = x # 横坐标j = y # 纵坐标while j < 19:if self.chessboard[j][i] is None:blank_score += 1blank_score_plus[1] += 1breakelif self.chessboard[j][i].color == color: color_score += 1color_score_plus[1] += 1else:breakif j >= y + 4: # 最近五个点breakj += 1# 正斜线# 右上i = xj = ywhile i < 19 and j >= 0:if self.chessboard[j][i] is None:blank_score += 1blank_score_plus[2] += 1breakelif self.chessboard[j][i].color == color: color_score += 1color_score_plus[2] += 1else:breakif i >= x + 4: # 最近五个点breaki += 1j -= 1# 左下i = xj = ywhile j < 19 and i >= 0:if self.chessboard[j][i] is None:blank_score += 1blank_score_plus[2] += 1breakelif self.chessboard[j][i].color == color: color_score += 1color_score_plus[2] += 1else:breakif j >= y + 4: # 最近五个点breakj = ywhile i >= 0 and j >= 0:if self.chessboard[j][i] is None:blank_score += 1blank_score_plus[3] += 1breakelif self.chessboard[j][i].color == color:color_score += 1color_score_plus[3] += 1else:breakif i <= x - 4:breaki -= 1j -= 1# 右上i = xj = ywhile i < 19 and j < 19:if self.chessboard[j][i] is None:blank_score += 1blank_score_plus[3] += 1breakelif self.chessboard[j][i].color == color:color_score += 1color_score_plus[3] += 1else:breakif i >= x + 4:breaki += 1j += 1for k in range(4):if color_score_plus[k] >= 5:return 100# color_score *= 5return max([x + y for x, y in zip(color_score_plus, blank_score_plus)]) def getPoint(self):'''返回落⼦位置:return:'''# 简单实现:返回⼀个空⽩交点# for i in range(19):# for j in range(19):# if self.chessboard[i][j] == None:# return QPoint(j, i)## 没有找到合适的点white_score = [ [ 0 for i in range(19) ] for j in range(19)]black_score = [ [ 0 for i in range(19) ] for j in range(19)]for i in range(19):for j in range(19):if self.chessboard[i][j] != None:continue# 模拟落⼦self.chessboard[i][j] = Chessman(color='white',parent=self)white_score[i][j] = self.getPointScore(j, i, 'white')self.chessboard[i][j].close()self.chessboard[i][j] = Noneself.chessboard[i][j] = Chessman(color='black',parent=self)black_score[i][j] = self.getPointScore(j, i, 'black')self.chessboard[i][j].close()self.chessboard[i][j] = Noneprint('----------------')r_white_score = []r_black_score = []for i in white_score:r_white_score.extend(i)for i in black_score:r_black_score.extend(i)# 找到分数最⼤值score = [ max(x,y) for x,y in zip(r_white_score,r_black_score) ]# 找到分数做⼤的下标chess_index = score.index(max(score))print(score,'\n',max(score))y = chess_index //19x = chess_index % 19return QPoint(x,y)def autoDown(self):'''⾃动落⼦:return:'''point = self.getPoint()# 注意:x,y坐标对应chess_index = (point.y(), point.x()) # 棋⼦在棋盘中的下标pos = QPoint(50+point.x()*30, 50+point.y()*30) # 棋⼦在棋盘中的坐标self.chessman = Chessman(color=self.turnChessColor, parent=self)self.chessman.setIndex(chess_index[1], chess_index[0])self.chessman.move(pos)self.chessman.show() # 显⽰棋⼦# 显⽰标识self.focusPoint.move(QPoint(pos.x() - 15, pos.y() - 15))self.focusPoint.show()self.focusPoint.raise_()self.chessboard[chess_index[0]][chess_index[1]] = self.chessman# 历史记录self.history.append((chess_index[0], chess_index[1], self.chessman.color))# 改变落⼦颜⾊if self.turnChessColor == 'black':self.turnChessColor = 'white'else:self.turnChessColor = 'black'# 判断输赢result = self.isWin(self.chessman)if result != None:print(result + '赢了')self.showResult(result)passif __name__ == '__main__':import cgitbcgitb.enable('text')a = QApplication(sys.argv)m = SinglePlayerGame()m.show()sys.exit(a.exec_())更多关于python游戏的精彩⽂章请点击查看以下专题:源码下载:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

python实现飞机大战游戏

python实现飞机大战游戏

python实现飞机⼤战游戏飞机⼤战(Python)代码分为两个python⽂件,⼯具类和主类,需要安装pygame模块,能完美运⾏(⽹上好多不完整的,调试得⼼累。

实现出来,成就感还是满满的),如图所⽰:完整代码如下:1.⼯具类plane_sprites.pyimport randomimport pygame# 屏幕⼤⼩的常量SCREEN_RECT = pygame.Rect(0, 0, 480, 700)# 刷新的帧率FRAME_PER_SEC = 60# 创建敌机的定时器常量CREATE_ENEMY_EVENT = EREVENT# 英雄发射⼦弹事件HERO_FIRE_EVENT = EREVENT + 1class GameSprite(pygame.sprite.Sprite):"""飞机⼤战游戏精灵"""def __init__(self, image_name, speed=1):super().__init__()# 调⽤⽗类的初始化⽅法self.image = pygame.image.load(image_name)# 定义对象的属性self.rect = self.image.get_rect()self.speed = speeddef update(self):# 在屏幕的垂直⽅向上移动self.rect.y += self.speedclass Background(GameSprite):"""游戏背景精灵"""def __init__(self, is_alt=False):super().__init__("C:/Users/Administrator/Desktop/background.png")# 1. 调⽤⽗类⽅法实现精灵的创建(image/rect/speed) if is_alt:# 2. 判断是否是交替图像,如果是,需要设置初始位置self.rect.y = -self.rect.heightdef update(self):super().update()# 1. 调⽤⽗类的⽅法实现if self.rect.y >= SCREEN_RECT.height:# 2. 判断是否移出屏幕,如果移出屏幕,将图像设置到屏幕的上⽅self.rect.y = -self.rect.heightclass Enemy(GameSprite):"""敌机精灵"""def __init__(self):super().__init__("C:/Users/Administrator/Desktop/enemy1.png")# 1. 调⽤⽗类⽅法,创建敌机精灵,同时指定敌机图⽚ self.speed = random.randint(1, 3)# 2. 指定敌机的初始随机速度 1 ~ 3self.rect.bottom = 0# 3. 指定敌机的初始随机位置max_x = SCREEN_RECT.width - self.rect.widthself.rect.x = random.randint(0, max_x)def update(self):super().update()# 1. 调⽤⽗类⽅法,保持垂直⽅向的飞⾏# 2. 判断是否飞出屏幕,如果是,需要从精灵组删除敌机if self.rect.y >= SCREEN_RECT.height:self.kill()# print("飞出屏幕,需要从精灵组删除...")# kill⽅法可以将精灵从所有精灵组中移出,精灵就会被⾃动销毁def __del__(self):# print("敌机挂了 %s" % self.rect)passclass Hero(GameSprite):"""英雄精灵"""def __init__(self):super().__init__("C:/Users/Administrator/Desktop/me1.png", 0)self.rect.centerx = SCREEN_RECT.centerxself.rect.bottom = SCREEN_RECT.bottom - 120self.bullets = pygame.sprite.Group()def update(self):self.rect.x += self.speedif self.rect.x < 0:self.rect.x = 0elif self.rect.right > SCREEN_RECT.right:self.rect.right = SCREEN_RECT.rightdef fire(self):print("发射⼦弹...")for i in (0, 1, 2):bullet = Bullet()bullet.rect.bottom = self.rect.y - i * 20bullet.rect.centerx = self.rect.centerxself.bullets.add(bullet)class Bullet(GameSprite):"""⼦弹精灵"""def __init__(self):super().__init__("C:/Users/Administrator/Desktop/bullet1.png", -2)def update(self):super().update()if self.rect.bottom < 0:self.kill()def __del__(self):print("⼦弹被销毁...")2.主类plane_main.pyimport pygamefrom plane_sprites import *class PlaneGame(object):"""飞机⼤战主游戏"""def __init__(self):print("游戏初始化")self.screen = pygame.display.set_mode(SCREEN_RECT.size)self.clock = pygame.time.Clock()self.__create_sprites()pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)pygame.time.set_timer(HERO_FIRE_EVENT, 500)def __create_sprites(self):bg1 = Background()bg2 = Background(True)self.back_group = pygame.sprite.Group(bg1, bg2)self.enemy_group = pygame.sprite.Group()self.hero = Hero()self.hero_group = pygame.sprite.Group(self.hero)def start_game(self):print("游戏开始...")while True:self.clock.tick(FRAME_PER_SEC)self.__event_handler()self.__check_collide()self.__update_sprites()pygame.display.update()def __event_handler(self):for event in pygame.event.get():if event.type == pygame.QUIT:PlaneGame.__game_over()elif event.type == CREATE_ENEMY_EVENT:# print("敌机出场...")# 创建敌机精灵enemy = Enemy()self.enemy_group.add(enemy)elif event.type == HERO_FIRE_EVENT:self.hero.fire()# elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:# print("向右移动...")keys_pressed = pygame.key.get_pressed()if keys_pressed[pygame.K_RIGHT]:self.hero.speed = 2elif keys_pressed[pygame.K_LEFT]:self.hero.speed = -2else:self.hero.speed = 0def __check_collide(self):for event in pygame.event.get():if event.type == pygame.QUIT:PlaneGame.__game_over()elif event.type == CREATE_ENEMY_EVENT:enemy = Enemy()self.enemy_group.add(enemy)elif event.type == HERO_FIRE_EVENT:self.hero.fire()keys_pressed = pygame.key.get_pressed()if keys_pressed[pygame.K_RIGHT]:self.hero.speed = 2elif keys_pressed[pygame.K_LEFT]:self.hero.speed = -2else:self.hero.speed = 0def __check_collide(self):pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)if len(enemies) > 0:self.hero.kill()PlaneGame.__game_over()def __update_sprites(self):self.back_group.update()self.back_group.draw(self.screen)self.enemy_group.update()self.enemy_group.draw(self.screen)self.hero_group.update()self.hero_group.draw(self.screen)self.hero.bullets.update()self.hero.bullets.draw(self.screen)@staticmethoddef __game_over():print("游戏结束")pygame.quit()exit()if __name__ == '__main__':game = PlaneGame()game.start_game()更多关于python游戏的精彩⽂章请点击查看以下专题:更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

Python实现人机中国象棋游戏

Python实现人机中国象棋游戏

Python实现⼈机中国象棋游戏⽬录导语1.游戏规则&基本玩法1.1 基本玩法1.2 ⾏棋规则2.素材⽂件3.主要代码3.1 Chinachess.py 为主⽂件3.2 Constants.py 数据常量3.3 Pieces.py 棋⼦类,⾛法3.4 Computer.py 电脑⾛法计算3.5 Button.py按钮定义4.游戏效果总结导语哈喽!哈喽!我是⽊⽊⼦!今⽇游戏更新——中国象棋上线啦!中国象棋是⼀种古⽼的棋类游戏,⼤约有两千年的历史。

是中华⽂明⾮物质⽂化经典产物,艺术价值泛属于整个⼈类⽂明进化史的⼀个分枝。

在中国,可以随处在⼤街上、⼩公园⼉⾥等地⽅经常看到⼀堆⼈围在⼀起下棋,这就⾜以说明中国象棋的流⾏性以及普遍性有多⾼!早前曾有统计,14、15个中国⼈当中,就有1个会下中国象棋。

中国象棋的受众,可能数以亿计!今天教⼤家制作⼀款中国象棋and想学象棋的话也可以来看看当作新⼿村吧~1.游戏规则&基本玩法1.1 基本玩法中国象棋的游戏⽤具由棋盘和棋⼦组成,对局时,由执红棋的⼀⽅先⾛,双⽅轮流各⾛⼀招,直⾄分出胜、负、和,对局即终了。

轮到⾛棋的⼀⽅,将某个棋⼦从⼀个交叉点⾛到另⼀个交叉点,或者吃掉对⽅的棋⼦⽽占领其交叉点,都算⾛了⼀着。

双⽅各⾛⼀着,称为⼀个回合。

1.2 ⾏棋规则2.素材⽂件3.主要代码chinachess.py 为主⽂件;constants.py 数据常量;pieces.py 棋⼦类,⾛法;computer.py 电脑⾛法计算;button.py按钮定义。

⽬前电脑⾛法⽐较傻,有兴趣的朋友可以对computer.py 进⾏升级!不过这针对⼤部分的新⼿刚开始学象棋的话完全够⽤了哈~哈哈哈如果你新⼿⼊门玩⼉的过电脑就说明你⼊门了!3.1 Chinachess.py 为主⽂件import pygameimport timeimport Xiangqi.constants as constantsfrom Xiangqi.button import Buttonimport Xiangqi.pieces as piecesimport puter as computerclass MainGame():window = NoneStart_X = constants.Start_XStart_Y = constants.Start_YLine_Span = constants.Line_SpanMax_X = Start_X + 8 * Line_SpanMax_Y = Start_Y + 9 * Line_Spanplayer1Color = constants.player1Colorplayer2Color = constants.player2ColorPutdownflag = player1ColorpiecesSelected = Nonebutton_go = NonepiecesList = []def start_game(self):MainGame.window = pygame.display.set_mode([constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT])pygame.display.set_caption("Python代码⼤全-中国象棋")MainGame.button_go = Button(MainGame.window, "重新开始", constants.SCREEN_WIDTH - 100, 300) # 创建开始按钮self.piecesInit()while True:time.sleep(0.1)# 获取事件MainGame.window.fill(constants.BG_COLOR)self.drawChessboard()#MainGame.button_go.draw_button()self.piecesDisplay()self.VictoryOrDefeat()puterplay()self.getEvent()pygame.display.update()pygame.display.flip()def drawChessboard(self): #画象棋盘mid_end_y = MainGame.Start_Y + 4 * MainGame.Line_Spanmin_start_y = MainGame.Start_Y + 5 * MainGame.Line_Spanfor i in range(0, 9):x = MainGame.Start_X + i * MainGame.Line_Spanif i==0 or i ==8:y = MainGame.Start_Y + i * MainGame.Line_Spanpygame.draw.line(MainGame.window, constants.BLACK, [x, MainGame.Start_Y], [x, MainGame.Max_Y], 1)else:pygame.draw.line(MainGame.window, constants.BLACK, [x, MainGame.Start_Y], [x, mid_end_y], 1)pygame.draw.line(MainGame.window, constants.BLACK, [x, min_start_y], [x, MainGame.Max_Y], 1)for i in range(0, 10):x = MainGame.Start_X + i * MainGame.Line_Spany = MainGame.Start_Y + i * MainGame.Line_Spanpygame.draw.line(MainGame.window, constants.BLACK, [MainGame.Start_X, y], [MainGame.Max_X, y], 1)speed_dial_start_x = MainGame.Start_X + 3 * MainGame.Line_Spanspeed_dial_end_x = MainGame.Start_X + 5 * MainGame.Line_Spanspeed_dial_y1 = MainGame.Start_Y + 0 * MainGame.Line_Spanspeed_dial_y2 = MainGame.Start_Y + 2 * MainGame.Line_Spanspeed_dial_y3 = MainGame.Start_Y + 7 * MainGame.Line_Spanspeed_dial_y4 = MainGame.Start_Y + 9 * MainGame.Line_Spanpygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y1], [speed_dial_end_x, speed_dial_y2], 1) pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y2],[speed_dial_end_x, speed_dial_y1], 1)pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y3],[speed_dial_end_x, speed_dial_y4], 1)pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y4],[speed_dial_end_x, speed_dial_y3], 1)def piecesInit(self): #加载棋⼦MainGame.piecesList.append(pieces.Rooks(MainGame.player2Color, 0,0))MainGame.piecesList.append(pieces.Rooks(MainGame.player2Color, 8, 0))MainGame.piecesList.append(pieces.Elephants(MainGame.player2Color, 2, 0))MainGame.piecesList.append(pieces.Elephants(MainGame.player2Color, 6, 0))MainGame.piecesList.append(pieces.King(MainGame.player2Color, 4, 0))MainGame.piecesList.append(pieces.Knighs(MainGame.player2Color, 1, 0))MainGame.piecesList.append(pieces.Knighs(MainGame.player2Color, 7, 0))MainGame.piecesList.append(pieces.Cannons(MainGame.player2Color, 1, 2))MainGame.piecesList.append(pieces.Cannons(MainGame.player2Color, 7, 2))MainGame.piecesList.append(pieces.Mandarins(MainGame.player2Color, 3, 0))MainGame.piecesList.append(pieces.Mandarins(MainGame.player2Color, 5, 0))MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 0, 3))MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 2, 3))MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 4, 3))MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 6, 3))MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 8, 3))MainGame.piecesList.append(pieces.Rooks(MainGame.player1Color, 0, 9))MainGame.piecesList.append(pieces.Rooks(MainGame.player1Color, 8, 9))MainGame.piecesList.append(pieces.Elephants(MainGame.player1Color, 2, 9))MainGame.piecesList.append(pieces.Elephants(MainGame.player1Color, 6, 9))MainGame.piecesList.append(pieces.King(MainGame.player1Color, 4, 9))MainGame.piecesList.append(pieces.Knighs(MainGame.player1Color, 1, 9))MainGame.piecesList.append(pieces.Knighs(MainGame.player1Color, 7, 9))MainGame.piecesList.append(pieces.Cannons(MainGame.player1Color, 1, 7))MainGame.piecesList.append(pieces.Cannons(MainGame.player1Color, 7, 7))MainGame.piecesList.append(pieces.Mandarins(MainGame.player1Color, 3, 9))MainGame.piecesList.append(pieces.Mandarins(MainGame.player1Color, 5, 9))MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 0, 6))MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 2, 6))MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 4, 6))MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 6, 6))MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 8, 6))def piecesDisplay(self):for item in MainGame.piecesList:item.displaypieces(MainGame.window)#MainGame.window.blit(item.image, item.rect)def getEvent(self):# 获取所有的事件eventList = pygame.event.get()for event in eventList:if event.type == pygame.QUIT:self.endGame()elif event.type == pygame.MOUSEBUTTONDOWN:pos = pygame.mouse.get_pos()mouse_x = pos[0]mouse_y = pos[1]if (mouse_x > MainGame.Start_X - MainGame.Line_Span / 2 and mouse_x < MainGame.Max_X + MainGame.Line_Span / 2) and ( mouse_y > MainGame.Start_Y - MainGame.Line_Span / 2 and mouse_y < MainGame.Max_Y + MainGame.Line_Span / 2):# print( str(mouse_x) + "" + str(mouse_y))# print(str(MainGame.Putdownflag))if MainGame.Putdownflag != MainGame.player1Color:returnclick_x = round((mouse_x - MainGame.Start_X) / MainGame.Line_Span)click_y = round((mouse_y - MainGame.Start_Y) / MainGame.Line_Span)click_mod_x = (mouse_x - MainGame.Start_X) % MainGame.Line_Spanclick_mod_y = (mouse_y - MainGame.Start_Y) % MainGame.Line_Spanif abs(click_mod_x - MainGame.Line_Span / 2) >= 5 and abs(click_mod_y - MainGame.Line_Span / 2) >= 5:# print("有效点:x="+str(click_x)+" y="+str(click_y))# 有效点击点self.PutdownPieces(MainGame.player1Color, click_x, click_y)else:print("out")if MainGame.button_go.is_click():#self.restart()print("button_go click")else:print("button_go click out")def PutdownPieces(self, t, x, y):selectfilter=list(filter(lambda cm: cm.x == x and cm.y == y and cm.player == MainGame.player1Color,MainGame.piecesList)) if len(selectfilter):MainGame.piecesSelected = selectfilter[0]returnif MainGame.piecesSelected :#print("1111")arr = pieces.listPiecestoArr(MainGame.piecesList)if MainGame.piecesSelected.canmove(arr, x, y):self.PiecesMove(MainGame.piecesSelected, x, y)MainGame.Putdownflag = MainGame.player2Colorelse:fi = filter(lambda p: p.x == x and p.y == y, MainGame.piecesList)listfi = list(fi)if len(listfi) != 0:MainGame.piecesSelected = listfi[0]def PiecesMove(self,pieces, x , y):for item in MainGame.piecesList:if item.x ==x and item.y == y:MainGame.piecesList.remove(item)pieces.x = xpieces.y = yprint("move to " +str(x) +" "+str(y))return Truedef Computerplay(self):if MainGame.Putdownflag == MainGame.player2Color:print("轮到电脑了")computermove = computer.getPlayInfo(MainGame.piecesList)#if computer==None:#returnpiecemove = Nonefor item in MainGame.piecesList:if item.x == computermove[0] and item.y == computermove[1]:piecemove= itemself.PiecesMove(piecemove, computermove[2], computermove[3])MainGame.Putdownflag = MainGame.player1Color#判断游戏胜利def VictoryOrDefeat(self):txt =""result = [MainGame.player1Color,MainGame.player2Color]for item in MainGame.piecesList:if type(item) ==pieces.King:if item.player == MainGame.player1Color:result.remove(MainGame.player1Color)if item.player == MainGame.player2Color:result.remove(MainGame.player2Color)if len(result)==0:returnif result[0] == MainGame.player1Color :txt = "失败!"else:txt = "胜利!"MainGame.window.blit(self.getTextSuface("%s" % txt), (constants.SCREEN_WIDTH - 100, 200))MainGame.Putdownflag = constants.overColordef getTextSuface(self, text):pygame.font.init()# print(pygame.font.get_fonts())font = pygame.font.SysFont('kaiti', 18)txt = font.render(text, True, constants.TEXT_COLOR) return txtdef endGame(self):print("exit")exit()if __name__ == '__main__':MainGame().start_game()3.2 Constants.py 数据常量#数据常量import pygameSCREEN_WIDTH=900SCREEN_HEIGHT=650Start_X = 50Start_Y = 50Line_Span = 60player1Color = 1player2Color = 2overColor = 3BG_COLOR=pygame.Color(200, 200, 200)Line_COLOR=pygame.Color(255, 255, 200)TEXT_COLOR=pygame.Color(255, 0, 0)# 定义颜⾊BLACK = ( 0, 0, 0)WHITE = (255, 255, 255)RED = (255, 0, 0)GREEN = ( 0, 255, 0)BLUE = ( 0, 0, 255)repeat = 0pieces_images = {'b_rook': pygame.image.load("imgs/s2/b_c.gif"),'b_elephant': pygame.image.load("imgs/s2/b_x.gif"),'b_king': pygame.image.load("imgs/s2/b_j.gif"),'b_knigh': pygame.image.load("imgs/s2/b_m.gif"),'b_mandarin': pygame.image.load("imgs/s2/b_s.gif"),'b_cannon': pygame.image.load("imgs/s2/b_p.gif"),'b_pawn': pygame.image.load("imgs/s2/b_z.gif"),'r_rook': pygame.image.load("imgs/s2/r_c.gif"),'r_elephant': pygame.image.load("imgs/s2/r_x.gif"),'r_king': pygame.image.load("imgs/s2/r_j.gif"),'r_knigh': pygame.image.load("imgs/s2/r_m.gif"),'r_mandarin': pygame.image.load("imgs/s2/r_s.gif"),'r_cannon': pygame.image.load("imgs/s2/r_p.gif"),'r_pawn': pygame.image.load("imgs/s2/r_z.gif"),}3.3 Pieces.py 棋⼦类,⾛法#棋⼦类,⾛法import pygameimport Xiangqi.constants as constantsclass Pieces():def __init__(self, player, x, y):self.imagskey = self.getImagekey()self.image = constants.pieces_images[self.imagskey]self.x = xself.y = yself.player = playerself.rect = self.image.get_rect()self.rect.left = constants.Start_X + x * constants.Line_Span - self.image.get_rect().width / 2self.rect.top = constants.Start_Y + y * constants.Line_Span - self.image.get_rect().height / 2def displaypieces(self,screen):#print(str(self.rect.left))self.rect.left = constants.Start_X + self.x * constants.Line_Span - self.image.get_rect().width / 2 self.rect.top = constants.Start_Y + self.y * constants.Line_Span - self.image.get_rect().height / 2 screen.blit(self.image,self.rect);#self.image = self.images#MainGame.window.blit(self.image,self.rect)def canmove(self, arr, moveto_x, moveto_y):passdef getImagekey(self):return Nonedef getScoreWeight(self,listpieces):return Noneclass Rooks(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_rook"else:return "b_rook"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y:return Falseif arr[moveto_x][moveto_y] ==self.player :return Falseif self.x == moveto_x:step = -1 if self.y > moveto_y else 1for i in range(self.y +step, moveto_y, step):if arr[self.x][i] !=0 :return False#print(" move y")return Trueif self.y == moveto_y:step = -1 if self.x > moveto_x else 1for i in range(self.x + step, moveto_x, step):if arr[i][self.y] != 0:return Falsereturn Truedef getScoreWeight(self, listpieces):score = 11return scoreclass Knighs(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_knigh"else:return "b_knigh"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y:return Falseif arr[moveto_x][moveto_y] == self.player:return False#print(str(self.x) +""+str(self.y))move_x = moveto_x-self.xmove_y = moveto_y - self.yif abs(move_x) == 1 and abs(move_y) == 2:step = 1 if move_y > 0 else -1if arr[self.x][self.y + step] == 0:return Trueif abs(move_x) == 2 and abs(move_y) == 1:step = 1 if move_x >0 else -1if arr[self.x +step][self.y] ==0 :return Truedef getScoreWeight(self, listpieces):score = 5return scoreclass Elephants(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_elephant"else:return "b_elephant"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y:return Falseif arr[moveto_x][moveto_y] == self.player:return Falseif self.y <=4 and moveto_y >=5 or self.y >=5 and moveto_y <=4: return Falsemove_x = moveto_x - self.xmove_y = moveto_y - self.yif abs(move_x) == 2 and abs(move_y) == 2:step_x = 1 if move_x > 0 else -1step_y = 1 if move_y > 0 else -1if arr[self.x + step_x][self.y + step_y] == 0:return Truedef getScoreWeight(self, listpieces):score = 2return scoreclass Mandarins(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_mandarin"else:return "b_mandarin"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y:return Falseif arr[moveto_x][moveto_y] == self.player:return Falseif moveto_x <3 or moveto_x >5:return Falseif moveto_y > 2 and moveto_y < 7:return Falsemove_x = moveto_x - self.xmove_y = moveto_y - self.yif abs(move_x) == 1 and abs(move_y) == 1:return Truedef getScoreWeight(self, listpieces):score = 2return scoreclass King(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_king"else:return "b_king"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y: return Falseif arr[moveto_x][moveto_y] == self.player:return Falseif moveto_x < 3 or moveto_x > 5:return Falseif moveto_y > 2 and moveto_y < 7:return Falsemove_x = moveto_x - self.xmove_y = moveto_y - self.yif abs(move_x) + abs(move_y) == 1:return Truedef getScoreWeight(self, listpieces):score = 150return scoreclass Cannons(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_cannon"else:return "b_cannon"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y: return Falseif arr[moveto_x][moveto_y] == self.player:return Falseoverflag = Falseif self.x == moveto_x:step = -1 if self.y > moveto_y else 1for i in range(self.y + step, moveto_y, step): if arr[self.x][i] != 0:if overflag:return Falseelse:overflag = Trueif overflag and arr[moveto_x][moveto_y] == 0: return Falseif not overflag and arr[self.x][moveto_y] != 0: return Falsereturn Trueif self.y == moveto_y:step = -1 if self.x > moveto_x else 1for i in range(self.x + step, moveto_x, step):if arr[i][self.y] != 0:if overflag:return Falseelse:overflag = Trueif overflag and arr[moveto_x][moveto_y] == 0:return Falseif not overflag and arr[moveto_x][self.y] != 0:return Falsereturn Truedef getScoreWeight(self, listpieces):score = 6return scoreclass Pawns(Pieces):def __init__(self, player, x, y):self.player = playersuper().__init__(player, x, y)def getImagekey(self):if self.player == constants.player1Color:return "r_pawn"else:return "b_pawn"def canmove(self, arr, moveto_x, moveto_y):if self.x == moveto_x and self.y == moveto_y:return Falseif arr[moveto_x][moveto_y] == self.player:return Falsemove_x = moveto_x - self.xmove_y = moveto_y - self.yif self.player == constants.player1Color:if self.y > 4 and move_x != 0 :return Falseif move_y > 0:return Falseelif self.player == constants.player2Color:if self.y <= 4 and move_x != 0 :return Falseif move_y < 0:return Falseif abs(move_x) + abs(move_y) == 1:return Truedef getScoreWeight(self, listpieces):score = 2return scoredef listPiecestoArr(piecesList):arr = [[0 for i in range(10)] for j in range(9)]for i in range(0, 9):for j in range(0, 10):if len(list(filter(lambda cm: cm.x == i and cm.y == j and cm.player == constants.player1Color, piecesList))):arr[i][j] = constants.player1Colorelif len(list(filter(lambda cm: cm.x == i and cm.y == j and cm.player == constants.player2Color, piecesList))):arr[i][j] = constants.player2Colorreturn arr3.4 Computer.py 电脑⾛法计算#电脑⾛法计算import Xiangqi.constants as constants#import timefrom Xiangqi.pieces import listPiecestoArrdef getPlayInfo(listpieces):pieces = movedeep(listpieces ,1 ,constants.player2Color)return [pieces[0].x,pieces[0].y, pieces[1], pieces[2]]def movedeep(listpieces, deepstep, player):arr = listPiecestoArr(listpieces)listMoveEnabel = []for i in range(0, 9):for j in range(0, 10):for item in listpieces:if item.player == player and item.canmove(arr, i, j):#标记是否有⼦被吃如果被吃在下次循环时需要补会piecesremove = Nonefor itembefore in listpieces:if itembefore.x == i and itembefore.y == j:piecesremove= itembeforebreakif piecesremove != None:listpieces.remove(piecesremove)#记录移动之前的位置move_x = item.xmove_y = item.yitem.x = iitem.y = j#print(str(move_x) + "," + str(move_y) + "," + str(item.x) + " , " + str(item.y))scoreplayer1 = 0scoreplayer2 = 0for itemafter in listpieces:if itemafter.player == constants.player1Color:scoreplayer1 += itemafter.getScoreWeight(listpieces)elif itemafter.player == constants.player2Color:scoreplayer2 += itemafter.getScoreWeight(listpieces)#print("得分:"+item.imagskey +", "+str(len(moveAfterListpieces))+","+str(i)+","+str(j)+"," +str(scoreplayer1) +" , "+ str(scoreplayer2) ) #print(str(deepstep))#如果得⼦判断对⾯是否可以杀过来,如果⼜被杀,⽽且⼦⼒评分低,则不⼲arrkill = listPiecestoArr(listpieces)if scoreplayer2 > scoreplayer1 :for itemkill in listpieces:if itemkill.player == constants.player1Color and itemkill.canmove(arrkill, i, j):scoreplayer2=scoreplayer1if deepstep > 0 :nextplayer = constants.player1Color if player == constants.player2Color else constants.player2Colornextpiecesbest= movedeep(listpieces, deepstep -1, nextplayer)listMoveEnabel.append([item, i, j, nextpiecesbest[3], nextpiecesbest[4], nextpiecesbest[5]])else:#print(str(len(listpieces)))#print("得分:" + item.imagskey + ", " + str(len(listpieces)) + "," + str(move_x) + "," + str(move_y) + "," + str(i) + " , " + str(j))if player == constants.player2Color:listMoveEnabel.append([item, i, j, scoreplayer1, scoreplayer2, scoreplayer1 - scoreplayer2])else:listMoveEnabel.append([item, i, j, scoreplayer1, scoreplayer2, scoreplayer2 - scoreplayer1])#print("得分:"+str(scoreplayer1))item.x = move_xitem.y = move_yif piecesremove != None:listpieces.append(piecesremove)list_scorepalyer1 = sorted(listMoveEnabel, key=lambda tm: tm[5], reverse=True)piecesbest = list_scorepalyer1[0]if deepstep ==1 :print(list_scorepalyer1)return piecesbest3.5 Button.py按钮定义#设置按钮import pygameclass Button():def __init__(self, screen, msg, left,top): # msg为要在按钮中显⽰的⽂本"""初始化按钮的属性"""self.screen = screenself.screen_rect = screen.get_rect()self.width, self.height = 150, 50 # 这种赋值⽅式很不错self.button_color = (72, 61, 139) # 设置按钮的rect对象颜⾊为深蓝self.text_color = (255, 255, 255) # 设置⽂本的颜⾊为⽩⾊pygame.font.init()self.font = pygame.font.SysFont('kaiti', 20) # 设置⽂本为默认字体,字号为40self.rect = pygame.Rect(0, 0, self.width, self.height)#self.rect.center = self.screen_rect.center # 创建按钮的rect对象,并使其居中self.left = leftself.top = topself.deal_msg(msg) # 渲染图像def deal_msg(self, msg):"""将msg渲染为图像,并将其在按钮上居中"""self.msg_img = self.font.render(msg, True, self.text_color, self.button_color) # render将存储在msg的⽂本转换为图像self.msg_img_rect = self.msg_img.get_rect() # 根据⽂本图像创建⼀个rectself.msg_img_rect.center = self.rect.center # 将该rect的center属性设置为按钮的center属性def draw_button(self):#self.screen.fill(self.button_color, self.rect) # 填充颜⾊self.screen.blit(self.msg_img, (self.left,self.top)) # 将该图像绘制到屏幕def is_click(self):point_x, point_y = pygame.mouse.get_pos()x = self.lefty = self.topw, h = self.msg_img.get_size()in_x = x < point_x < x + win_y = y < point_y < y + hreturn in_x and in_y4.游戏效果总结好啦!⽂章就写到这⾥了哈,想⼊门象棋的可以先试着⾃⼰研究下,上⾯的教程也有说⾛法、⾏棋的规则,然后后⾯就是实战,⾃⼰动⼿跟电脑来⼀场对决吧~以上就是Python实现⼈机中国象棋游戏的详细内容,更多关于Python中国象棋的资料请关注其它相关⽂章!。

【python】10分钟教你用Python做个打飞机小游戏超详细教程

【python】10分钟教你用Python做个打飞机小游戏超详细教程

【python】10分钟教你⽤Python做个打飞机⼩游戏超详细教程整体框架开始之前-精灵类Sprite⼦弹类class Bullet玩家飞机类class Player敌机类class Enemy游戏主体循环以及帧率设置让⼦弹飞刷出敌机 打怪把飞机敌机⼦弹都画出来处理键盘事件分数显⽰ 和 GameOver最终代码这次还是⽤python的pygame库来做的游戏。

关于这个库的内容,读者可以上⽹了解⼀下。

本⽂只讲解⽤到的知识。

代码参考⾃⽹上,⾃⼰也做了⼀点代码简化。

尽量把最核⼼的⽅⾯⽤最简单的⽅式呈现给⼤家,让⼤家尽快掌握这个游戏的框架。

⾄于那些华丽的功能,⼤家在弄懂了核⼼知识以后,再去添加也是⾮常easy的。

这个游戏设计⽤到了⾯向对象的编程思想。

游戏主体划分为三个主要的类:⼦弹类class Bullet玩家类class Player敌机类class Enemy在屏幕上可见的也就是这三个东西了。

⾃⼰的飞机、敌⼈的飞机、⼦弹。

因此整个游戏的核⼼就是:把这三个东西的图像呈现在屏幕上。

判断和处理⼦弹撞击敌机和敌机撞击玩家这两种情况。

下⾯我们会展开为⼤家⼀⼀讲解。

在下⾯的代码中,你们会⼤量见到这个pygame.sprite模块。

这⾥就给⼤家介绍⼀下。

“sprite”,中⽂翻译“精灵”,在游戏动画⼀般是指⼀个独⽴运动的画⾯元素,在pygame中,就可以是⼀个带有图像(Surface)和⼤⼩位置(Rect)的对象。

简单来说是⼀个会动图⽚。

它的两个成员变量self.image=要显⽰图⽚的Surfaceself.rect = 显⽰Surface的区域对于self.rect,常⽤的设置rect的⽅法:self.rect = self.image.get_rect()。

然后设定self.rect.topleft=(0,0)来设定左上⾓的位置,从⽽设定这个精灵在屏幕上的显⽰位置。

精灵特别适合⽤在OO语⾔中,⽐如Python。

python项目飞机大战

python项目飞机大战

python项⽬飞机⼤战实现步骤1.创建窗⼝2.创建⼀个玩家飞机,按⽅向键可以左右移动3.给玩家飞机添加按空格键发射⼦弹功能4.创建⼀个敌机5.敌机⾃动左右移动6.敌机⾃动发射⼦弹1.创建窗⼝import pygameimport timedef main():#1.创建窗⼝screen = pygame.display.set_mode((480,852))#2 创建⼀个背景图⽚background = pygame.image.load('./feiji/background.png')while True:#3 显⽰到屏幕screen.blit(background,(0,0))pygame.display.update()time.sleep(0.05)if __name__ == '__main__':main()2.显⽰玩家飞机,检测键盘,控制飞机左右移动import pygameimport timefrom pygame.locals import *class HeroPlane(object):def __init__(self,screen_temp):self.x = 210self.y = 700self.screen = screen_temp #游戏窗⼝self.image = pygame.image.load('feiji/hero1.png')def display(self):self.screen.blit(self.image,(self.x,self.y)) #加载玩家飞机到窗⼝def move_left(self):self.x -= 5def move_right(self):self.x += 5def key_control(hero_temp):# 获取事件,⽐如按键等for event in pygame.event.get():# 判断是否是点击了退出按钮if event.type == QUIT:print("exit")exit()# 判断是否是按下了键elif event.type == KEYDOWN:# 检测按键是否是a或者leftif event.key == K_a or event.key == K_LEFT:print('left')hero_temp.move_left()# 检测按键是否是d或者rightelif event.key == K_d or event.key == K_RIGHT:print('right')hero_temp.move_right()# 检测按键是否是空格键elif event.key == K_SPACE:print('space')def main():#1.创建窗⼝screen = pygame.display.set_mode((480,852),0,0)#2 创建⼀个背景图⽚background = pygame.image.load('./feiji/background.png') # 创建⼀个飞机对象hero = HeroPlane(screen)while True:#把背景图⽚放到窗⼝显⽰screen.blit(background,(0,0))#显⽰玩家飞机到定义的(x,y)坐标位置hero.display()pygame.display.update()#检测键盘,控制玩家飞机移动key_control(hero)time.sleep(0.05)if __name__ == '__main__':main()3.玩家发射⼦弹import pygameimport timefrom pygame.locals import *class HeroPlane(object):def __init__(self,screen_temp):self.x = 210self.y = 700self.screen = screen_temp #游戏窗⼝self.image = pygame.image.load('feiji/hero1.png')self.bullet_list = [] #存储发射出去的⼦弹def display(self):# 加载玩家飞机到窗⼝self.screen.blit(self.image,(self.x,self.y))for bullet in self.bullet_list:bullet.display()bullet.move()def move_left(self):self.x -= 5def move_right(self):self.x += 5def fire(self):self.bullet_list.append(Bullet(self.screen,self.x,self.y)) class Bullet(object):def __init__(self,screen_temp,x,y):self.x = x + 40self.y = y - 20self.screen = screen_tempself.image = pygame.image.load('feiji/bullet.png')def display(self):self.screen.blit(self.image,(self.x,self.y))def move(self):self.y -= 20def key_control(hero_temp):# 获取事件,⽐如按键等for event in pygame.event.get():# 判断是否是点击了退出按钮if event.type == QUIT:print("exit")exit()# 判断是否是按下了键elif event.type == KEYDOWN:# 检测按键是否是a或者leftif event.key == K_a or event.key == K_LEFT:print('left')hero_temp.move_left()# 检测按键是否是d或者rightelif event.key == K_d or event.key == K_RIGHT: print('right')hero_temp.move_right()# 检测按键是否是空格键elif event.key == K_SPACE:print('space')hero_temp.fire()def main():#1.创建窗⼝screen = pygame.display.set_mode((480,852),0,0)#2 创建⼀个背景图⽚background = pygame.image.load('./feiji/background.png') # 创建⼀个飞机对象hero = HeroPlane(screen)while True:#把背景图⽚放到窗⼝显⽰screen.blit(background,(0,0))#显⽰玩家飞机到定义的(x,y)坐标位置hero.display()pygame.display.update()#检测键盘,控制玩家飞机移动key_control(hero)time.sleep(0.05)if __name__ == '__main__':main()效果如下:4.创建⼀个敌机--snip--class EnemyPlane(object):def __init__(self,screen_temp):self.x = 0self.y = 0self.screen = screen_tempself.image = pygame.image.load('feiji/enemy0.png')def display(self):self.screen.blit(self.image,(self.x,self.y))--snip--def main():--snip--#4 创建⼀个敌机enemy = EnemyPlane(screen)while True:--snip--enemy.display()--snip5.控制敌机左右移动--snip--class EnemyPlane(object):def __init__(self,screen_temp):--snip--self.direction = 'right' #定义敌机默认往右移动--snip--def move(self):if self.direction == 'right':self.x += 8elif self.direction == 'left':self.x -= 8if self.x > 430:self.direction = 'left'elif self.x < 0:self.direction = 'right'--snip--def main():--snip--#4 创建⼀个敌机enemy = EnemyPlane(screen)enemy.move() --snip--import pygameimport timefrom pygame.locals import *class HeroPlane(object):def __init__(self,screen_temp):self.x = 210self.y = 700self.screen = screen_temp #游戏窗⼝self.image = pygame.image.load('feiji/hero1.png')self.bullet_list = [] #存储发射出去的⼦弹def display(self):# 加载玩家飞机到窗⼝self.screen.blit(self.image,(self.x,self.y))for bullet in self.bullet_list:bullet.display()bullet.move()def move_left(self):self.x -= 5def move_right(self):self.x += 5def fire(self):self.bullet_list.append(Bullet(self.screen,self.x,self.y)) class EnemyPlane(object):def __init__(self,screen_temp):self.x = 0self.y = 0self.screen = screen_tempself.image = pygame.image.load('feiji/enemy0.png') self.direction = 'right' #定义敌机默认往右移动def display(self):self.screen.blit(self.image,(self.x,self.y))def move(self):if self.direction == 'right':self.x += 8elif self.direction == 'left':self.x -= 8if self.x > 430:self.direction = 'left'elif self.x < 0:self.direction = 'right'class Bullet(object):def __init__(self,screen_temp,x,y):self.x = x + 40self.y = y - 20self.screen = screen_tempself.image = pygame.image.load('feiji/bullet.png')def display(self):self.screen.blit(self.image,(self.x,self.y))def move(self):self.y -= 20def key_control(hero_temp):# 获取事件,⽐如按键等for event in pygame.event.get():# 判断是否是点击了退出按钮if event.type == QUIT:print("exit")exit()# 判断是否是按下了键elif event.type == KEYDOWN:# 检测按键是否是a或者leftif event.key == K_a or event.key == K_LEFT:print('left')hero_temp.move_left()# 检测按键是否是d或者rightelif event.key == K_d or event.key == K_RIGHT: print('right')hero_temp.move_right()# 检测按键是否是空格键elif event.key == K_SPACE:print('space')hero_temp.fire()def main():#1.创建窗⼝screen = pygame.display.set_mode((480,852),0,0)#2 创建⼀个背景图⽚background = pygame.image.load('./feiji/background.png') #3 创建⼀个飞机对象hero = HeroPlane(screen)#4 创建⼀个敌机enemy = EnemyPlane(screen)while True:#把背景图⽚放到窗⼝显⽰screen.blit(background,(0,0))#显⽰玩家飞机到定义的(x,y)坐标位置hero.display()enemy.display()enemy.move()pygame.display.update()#检测键盘,控制玩家飞机移动key_control(hero)time.sleep(0.05)if __name__ == '__main__':main()完整代码6.删除⼦弹,只要发射出去的⼦弹超过边界就删掉--snip--class HeroPlane(object):--snip----snip--bullet.move()if bullet.judge(): #判断⼦弹是否越界self.bullet_list.remove(bullet)--snip--class Bullet(object):--sinp--def judge(self):if self.y < 0:return Trueelse:return False--snipimport pygameimport timefrom pygame.locals import *class HeroPlane(object):def __init__(self,screen_temp):self.x = 210self.y = 700self.screen = screen_temp #游戏窗⼝self.image = pygame.image.load('feiji/hero1.png')self.bullet_list = [] #存储发射出去的⼦弹def display(self):# 加载玩家飞机到窗⼝self.screen.blit(self.image,(self.x,self.y))for bullet in self.bullet_list:bullet.display()bullet.move()if bullet.judge(): #判断⼦弹是否越界self.bullet_list.remove(bullet)def move_left(self):self.x -= 5def move_right(self):self.x += 5def fire(self):self.bullet_list.append(Bullet(self.screen,self.x,self.y)) class EnemyPlane(object):def __init__(self,screen_temp):self.x = 0self.y = 0self.screen = screen_tempself.image = pygame.image.load('feiji/enemy0.png') self.direction = 'right' #定义敌机默认往右移动def display(self):self.screen.blit(self.image,(self.x,self.y))def move(self):if self.direction == 'right':self.x += 8elif self.direction == 'left':self.x -= 8if self.x > 430:self.direction = 'left'elif self.x < 0:self.direction = 'right'class Bullet(object):def __init__(self,screen_temp,x,y):self.x = x + 40self.y = y - 20self.screen = screen_tempself.image = pygame.image.load('feiji/bullet.png')def display(self):self.screen.blit(self.image,(self.x,self.y))def move(self):self.y -= 20def judge(self):if self.y < 200:return Trueelse:return Falsedef key_control(hero_temp):# 获取事件,⽐如按键等for event in pygame.event.get():# 判断是否是点击了退出按钮if event.type == QUIT:print("exit")exit()# 判断是否是按下了键elif event.type == KEYDOWN:# 检测按键是否是a或者leftif event.key == K_a or event.key == K_LEFT:print('left')hero_temp.move_left()# 检测按键是否是d或者rightelif event.key == K_d or event.key == K_RIGHT:print('right')hero_temp.move_right()# 检测按键是否是空格键elif event.key == K_SPACE:print('space')hero_temp.fire()def main():#1.创建窗⼝screen = pygame.display.set_mode((480,852),0,0)#2 创建⼀个背景图⽚background = pygame.image.load('./feiji/background.png')#3 创建⼀个飞机对象hero = HeroPlane(screen)#4 创建⼀个敌机enemy = EnemyPlane(screen)while True:#把背景图⽚放到窗⼝显⽰screen.blit(background,(0,0))#显⽰玩家飞机到定义的(x,y)坐标位置hero.display()enemy.display()enemy.move()pygame.display.update()#检测键盘,控制玩家飞机移动key_control(hero)time.sleep(0.05)if __name__ == '__main__':main()完整代码7.添加敌机放射⼦弹功能使⽤random来控制敌机发射⼦弹的频率--snip--import randomclass EnemyPlane(object):--snip - -self.bullet_list = [] #存储发射出去的⼦弹self.direction = 'right' #定义敌机默认往右移动def display(self):--snip - -bullet.move()if bullet.judge(): #判断⼦弹是否越界self.bullet_list.remove(bullet)--snip--def fire(self):#控制⼦弹频率random_num = random.randint(1,80)if random_num == 10 or random_num == 40:self.bullet_list.append(EnemyBullet(self.screen,self.x,self.y)) --snip--class EnemyBullet(object):def __init__(self,screen_temp,x,y):self.x = x + 25self.y = y + 40self.screen = screen_tempself.image = pygame.image.load('feiji/bullet1.png')def display(self):self.screen.blit(self.image,(self.x,self.y))def move(self):self.y += 10def judge(self):if self.y > 852:return Trueelse:return False--snip - -while True:--snip - -enemy.move()enemy.fire()--snip--import pygameimport timefrom pygame.locals import *import randomclass HeroPlane(object):def __init__(self,screen_temp):self.x = 210self.y = 700self.screen = screen_temp #游戏窗⼝self.image = pygame.image.load('feiji/hero1.png')self.bullet_list = [] #存储发射出去的⼦弹def display(self):# 加载玩家飞机到窗⼝self.screen.blit(self.image,(self.x,self.y))for bullet in self.bullet_list:bullet.display()bullet.move()if bullet.judge(): #判断⼦弹是否越界self.bullet_list.remove(bullet)def move_left(self):self.x -= 5def move_right(self):self.x += 5def fire(self):self.bullet_list.append(Bullet(self.screen,self.x,self.y)) class EnemyPlane(object):def __init__(self,screen_temp):self.x = 0self.y = 0self.screen = screen_tempself.image = pygame.image.load('feiji/enemy0.png') self.bullet_list = [] #存储发射出去的⼦弹self.direction = 'right' #定义敌机默认往右移动def display(self):self.screen.blit(self.image,(self.x,self.y))for bullet in self.bullet_list:bullet.display()bullet.move()if bullet.judge(): #判断⼦弹是否越界self.bullet_list.remove(bullet)def move(self):if self.direction == 'right':self.x += 8elif self.direction == 'left':self.x -= 8if self.x > 430:self.direction = 'left'elif self.x < 0:self.direction = 'right'def fire(self):random_num = random.randint(1,80)if random_num == 10 or random_num == 40:self.bullet_list.append(EnemyBullet(self.screen,self.x,self.y)) class Bullet(object):def __init__(self,screen_temp,x,y):self.x = x + 40self.y = y - 20self.screen = screen_tempself.image = pygame.image.load('feiji/bullet.png')def display(self):self.screen.blit(self.image,(self.x,self.y))def move(self):self.y -= 20def judge(self):if self.y < 0:return Trueelse:return Falseclass EnemyBullet(object):def __init__(self,screen_temp,x,y):self.x = x + 25self.y = y + 40self.screen = screen_tempself.image = pygame.image.load('feiji/bullet1.png')def display(self):self.screen.blit(self.image,(self.x,self.y))def move(self):self.y += 10def judge(self):if self.y > 852:return Trueelse:return Falsedef key_control(hero_temp):# 获取事件,⽐如按键等for event in pygame.event.get():# 判断是否是点击了退出按钮if event.type == QUIT:print("exit")exit()# 判断是否是按下了键elif event.type == KEYDOWN:# 检测按键是否是a或者leftif event.key == K_a or event.key == K_LEFT:print('left')hero_temp.move_left()# 检测按键是否是d或者rightelif event.key == K_d or event.key == K_RIGHT:print('right')hero_temp.move_right()# 检测按键是否是空格键elif event.key == K_SPACE:print('space')hero_temp.fire()def main():#1.创建窗⼝screen = pygame.display.set_mode((480,852),0,0)#2 创建⼀个背景图⽚background = pygame.image.load('./feiji/background.png')#3 创建⼀个飞机对象hero = HeroPlane(screen)#4 创建⼀个敌机enemy = EnemyPlane(screen)while True:#把背景图⽚放到窗⼝显⽰screen.blit(background,(0,0))#显⽰玩家飞机到定义的(x,y)坐标位置hero.display()enemy.display()enemy.move()enemy.fire()pygame.display.update()#检测键盘,控制玩家飞机移动key_control(hero)time.sleep(0.05)if __name__ == '__main__':main()完整代码最终效果8.优化代码,创建基类1 import pygame2 import time3 from pygame.locals import *4 import random56 class BasePlane(object):7 '''飞机类'''8 def __init__(self,screen_temp,x,y,image_name):9 self.x = x10 self.y = y11 self.screen = screen_temp #游戏窗⼝12 self.image = pygame.image.load(image_name)13 self.bullet_list = [] #存储发射出去的⼦弹1415 def display(self):16 # 加载飞机到窗⼝17 self.screen.blit(self.image,(self.x,self.y))18 #控制⼦弹19 for bullet in self.bullet_list:20 bullet.display()21 bullet.move()22 if bullet.judge(): #判断⼦弹是否越界23 self.bullet_list.remove(bullet)2425 class HeroPlane(BasePlane):26 '''玩家飞机'''27 def __init__(self,screen_temp):28 BasePlane.__init__(self,screen_temp,210,700,'feiji/hero1.png')2930 def move_left(self):31 self.x -= 53233 def move_right(self):34 self.x += 53536 def fire(self):37 #发射⼦弹38 self.bullet_list.append(Bullet(self.screen,self.x,self.y))3940 class EnemyPlane(BasePlane):41 '''敌⽅飞机'''42 def __init__(self, screen_temp):43 BasePlane.__init__(self, screen_temp, 0, 0, 'feiji/enemy0.png')44 self.direction = 'right' #定义敌机默认往右移动4546 def move(self):47 if self.direction == 'right':48 self.x += 849 elif self.direction == 'left':50 self.x -= 85152 if self.x > 430:53 self.direction = 'left'54 elif self.x < 0:55 self.direction = 'right'5657 def fire(self):58 # 发射⼦弹59 random_num = random.randint(1,50)60 if random_num == 10 or random_num == 40:61 self.bullet_list.append(EnemyBullet(self.screen,self.x,self.y))6263 class BaseBullet(object):64 '''⼦弹类'''65 def __init__(self,screen_temp,x,y,image_name):66 self.x = x67 self.y = y68 self.screen = screen_temp69 self.image = pygame.image.load(image_name)7071 def display(self):72 self.screen.blit(self.image,(self.x,self.y))7374 class Bullet(BaseBullet):75 '''玩家⼦弹'''76 def __init__(self,screen_temp,x,y):77 BaseBullet.__init__(self,screen_temp,x+40,y-20,'feiji/bullet.png')7879 def move(self):80 self.y -= 208182 def judge(self):83 if self.y < 0:84 return True85 else:86 return False8788 class EnemyBullet(BaseBullet):89 '''敌机⼦弹'''90 def __init__(self,screen_temp,x,y):91 BaseBullet.__init__(self, screen_temp, x + 25, y + 40, 'feiji/bullet1.png')9293 def move(self):94 self.y += 109596 def judge(self):97 if self.y > 852:98 return True99 else:100 return False101102 def key_control(hero_temp):103 # 获取事件,⽐如按键等104 for event in pygame.event.get():105 # 判断是否是点击了退出按钮106 if event.type == QUIT:107 print("exit")108 exit()109 # 判断是否是按下了键110 elif event.type == KEYDOWN:111 # 检测按键是否是a或者left112 if event.key == K_a or event.key == K_LEFT:113 print('left')114 hero_temp.move_left()115116 # 检测按键是否是d或者right117 elif event.key == K_d or event.key == K_RIGHT: 118 print('right')119 hero_temp.move_right()120 # 检测按键是否是空格键121 elif event.key == K_SPACE:122 print('space')123 hero_temp.fire()124125 def main():126 #1.创建窗⼝127 screen = pygame.display.set_mode((480,852),0,0)128 #2 创建⼀个背景图⽚129 background = pygame.image.load('./feiji/background.png') 130 #3 创建⼀个飞机对象131 hero = HeroPlane(screen)132 #4 创建⼀个敌机对象133 enemy = EnemyPlane(screen)134135 while True:136 #把背景图⽚放到窗⼝显⽰137 screen.blit(background,(0,0))138 #显⽰玩家飞机到定义的(x,y)坐标位置139 hero.display() #显⽰玩家飞机140 enemy.display() #显⽰敌机141 enemy.move() #玩家飞机移动142 enemy.fire() #玩家飞机发射⼦弹143 pygame.display.update() #刷新144 #检测键盘,控制玩家飞机移动145 key_control(hero)146 time.sleep(0.05)147148 if __name__ == '__main__':149 main()。

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

elif player_score>com_score: print(‘玩家赢’)
else: print(‘电脑赢,玩家惨败’)
项目总结
项目总结
完成一个项目的流程 1.明确项目目标 2. 分析过程,拆解相项 3.逐步执行,代码实现 最后:还需要耐心、细心,不急不噪 罗马城不是一日建成的,日子久了,量变定会引起质变
玩家2 电脑2
玩家3 电脑3
玩家的出拳数值与电脑的出拳数值相等
代码逻辑: if per_fist==com_fist :
print(‘平局’)
(2)玩家赢
思维逻辑: 石头 VS 剪刀 or 剪刀VS 布
or 布 VS 石头
玩家1 电脑2
玩家2 电脑3
玩家3 电脑1
代码逻辑: elif ( per_fist==1 and com_fist==2) or
( per_fist==2 and com_fist==3) or
(per_fist==3 an脑赢 其它情况
else:
print(‘电脑赢’)
项目分解-版本3.0根据对战结果评输赢
项目分解-版本4.0实现多次对战
while循环循环语法结构
项目分解-2.0实现一次对战-双方出拳
涉及知识点:
随机数的产生: 导入random模块 ran=random.randint(n,m) 产生一个[n,m]之间的整数
项目分解-版本3.0根据对战结果评输赢
评定输赢的标准
(1)平局
思维逻辑:石头VS石头 or 剪刀VS剪刀 or 布VS 布
玩家1 电脑1
(1)初始化变量 answer=input(‘Are you ready?’)
(2)条件判断 while answer==‘y’: (3)循环操作评判输赢 ...... (4)改变变量 answer=input(‘继续吗?’)
项目分解-版本5.0实现最终结果的评判
解决思路
(1)声明两个变量分别用于存储玩家和电脑的对 战积分
平局双方不加分 赢方加1分 输方不加分
(2)循环结束统计对战积分,积分高的为最后的 赢家,积分相等平局
项目分解-版本5.0实现最终结果的评判
项目总结
思维逻辑
分数相同 平局 玩家分数大于电脑人物分数 玩家赢 其它情况 电脑赢
代码逻辑
If player_score==com_score : print(‘平局’)
Python实现的人机对战小游戏
——<石头、 剪刀、布>
各版本程序功能描述
版本1.0 获取双方对战人员名单 版本2.0实现一次对战 版本3.0根据对战结果评输赢 版本4.0实现多次对战 版本5.0实现最终结果的评判
项目分解-1.0版获取双方对战人员名单
涉及知识点:
(1)print()向控制台输出信息 (2)input()从键盘录入信息,结果为str类型 (3)控制台文本样式
相关文档
最新文档