python编写双人游戏
发布日期:2023-05-26 13:15:57
浏览次数:6
分类:技术文章
本文共 2068 字,大约阅读时间需要 6 分钟。
小编给大家准备了一个简单的双人游戏的示例代码,这个游戏叫做“石头剪刀布”。
游戏规则:
1. 玩家1和玩家2轮流出拳,可以选择石头、剪刀或布。
2. 石头胜剪刀,剪刀胜布,布胜石头。
3. 每轮游戏结束后,显示双方出拳和胜负结果。
4. 游戏结束后,显示双方的总胜利次数。
下面是代码实现:
import random# 定义游戏规则rules = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'}# 定义玩家类class Player: def __init__(self, name): self.name = name self.score = 0 def choose(self): # 玩家出拳 choice = input(f"{self.name}, please choose rock, scissors or paper: ") while choice not in rules: choice = input(f"{self.name}, please choose rock, scissors or paper: ") return choice def win(self): # 胜利时分数加1 self.score += 1 print(f"{self.name} wins!") def lose(self): print(f"{self.name} loses!") def draw(self): print("Draw!")# 定义游戏类class Game: def __init__(self): self.player1 = Player("Player 1") self.player2 = Player("Player 2") def play(self): # 游戏开始 print("Game start!") while True: # 玩家1出拳 p1_choice = self.player1.choose() # 玩家2出拳 p2_choice = self.player2.choose() # 判断胜负 if rules[p1_choice] == p2_choice: self.player1.win() self.player2.lose() elif rules[p2_choice] == p1_choice: self.player2.win() self.player1.lose() else: self.player1.draw() self.player2.draw() # 显示当前得分 print(f"Current score: {self.player1.name} {self.player1.score} : {self.player2.score} {self.player2.name}") # 判断是否结束游戏 if self.player1.score == 3 or self.player2.score == 3: break # 游戏结束 print("Game over!") if self.player1.score > self.player2.score: print(f"{self.player1.name} wins!") elif self.player2.score > self.player1.score: print(f"{self.player2.name} wins!") else: print("Draw!")# 开始游戏game = Game()game.play()
运行代码后,你可以看到游戏开始,然后玩家1和玩家2轮流出拳,直到有一方获得3次胜利为止,最后显示胜利者。
最后,希望大家多多支持!
注:转载请注明出处
转载地址:https://blog.csdn.net/m0_53697837/article/details/130471852 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月08日 21时57分24秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
spring boot 与 Ant Design of Vue 实现删除按钮(十八)
2021-06-30
spring boot 与 Ant Design of Vue 实现新增角色(二十)
2021-06-30
spring boot 与 Ant Design of Vue 实现修改角色(二十一)
2021-06-30
spring boot 与 Ant Design of Vue 实现删除角色(补二十一)
2021-06-30
spring boot 与 Ant Design of Vue 实现左侧组织树(二十三)
2021-06-30
spring boot 与 Ant Design of Vue 实现新增组织(二十四)
2021-06-30
spring boot 与 Ant Design of Vue 实现修改组织(二十五)
2021-06-30
spring boot 与 Ant Design of Vue 实现删除组织(二十六)
2021-06-30
spring boot 与 Ant Design of Vue 实现新增用户(二十八)
2021-06-30
spring boot 与 Ant Design of Vue 实现修改用户(二十九)
2021-06-30
spring boot 与 Ant Design of Vue 实现删除用户(三十)
2021-06-30
Druid连接池实现自定义场景的多数据库的连接
2021-06-30
CentOs7命令行(静默)的方式安装oracle数据库
2021-06-30
基于VMware安装CentOs7的镜像
2021-06-30
PL/SQL数据库管理工具的使用
2021-06-30