21点源代码
C语言21点游戏
C语言21点游戏#include#include#include#include#includeint Bookies_score=1000,/*庄家金币*/Rlayer_score=1000;//玩家金币int Bookiesscore=0,/*庄家当前点数*/Rlayerscore=0;//玩家当前点数int Random,/*玩家随机数*/Randoms;//庄家随机数int Bets_P;//玩家下注int Card;//是否发牌int i=1;int s=1;int main(void){Star_interface();//开始界面getch();system("CLS");//---------------------------------以下为产生玩家随机数发牌代码Judge_WorL();//输或者赢函数}//------------以下开始界面int Star_interface(){int i;system("color 9B");printf("\t\t\t C语言游戏:二十一点\n");printf("\n\n\n\n\n\n\n");printf(" 〓〓〓〓〓〓〓〓");printf("\n 〓\n 〓〓〓〓〓〓〓〓〓〓〓〓〓〓\n 〓\n 〓\n");printf(" 〓〓〓〓〓〓〓〓\n");printf("\n\n");printf("\t\t\t ①:查看规则②:开始游戏\n\n");printf("\t\t\t 制作人:小二\n\n");printf("\t\t\t 版本号:1.0\n\t\t\t");scanf("%d",&i);switch(i){case 1:system("CLS");printf("\t\t\t 二十一点游戏规则\n\n\n\t 介绍:手中所有的牌点数之和不超过21点,谁更接近21点,就赢得游戏。
Python扑克牌21点游戏实例代码
Python扑克牌21点游戏实例代码废话还是说太多了直接上代码import randomimport sys# 牌⾯列表card_code = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']# 花⾊列表card_symbol = ['♦', '♣', '♥', '♠']# 游戏初始化def init(player_count):# 根据玩家数来⽣成玩家记牌器player_group = [[] for _ in range(player_count)]# 根据玩家数来⽣成玩家是否要牌player_isWant = [True for _ in range(player_count)]# ⽣成元素1~52的列表 (去掉⼤⼩⿁的扑克牌[52张])poker = list(range(1, 53))# ⽤random的shuffle函数对列表打乱顺序 (洗牌)random.shuffle(poker)# 返回玩家组玩家是否要牌乱序52张扑克return player_group, player_isWant, poker# 打印玩家点数def print_player_point(player_group):# 存放玩家点数player_point = []# 遍历每⼀位玩家for index in range(len(player_group)):# 打印每位玩家的牌和点数print("-------玩家"+str(index+1)+"------")# 初始化玩家点数如果含有牌A 因为A可视为1点或11点则有两种点数current_player = [0, 0]# 遍历每位玩家的⼿牌for card in player_group[index]:"""核⼼代码由于牌⾯的数字是从1到52 所以牌⾯要先减1再求余才是牌⾯列表真正的下标若玩家抽到牌为15 即牌⾯为15 - 13 = 2 且按花⾊顺序为♣即2♣牌⾯ 15 - 1 = 14 再 14 % 13 = 1 这个就是对应牌⾯列表的第⼆位元素即2花⾊ 15 - 1 = 14 再 14 / 13 = 1 对应花⾊列表第⼆位元素即♣"""# 获取牌⾯和花⾊下标code_index = int((card - 1) % 13)symbol_index = int((card - 1) / 13)# 打印玩家牌信息print(card_code[code_index] + card_symbol[symbol_index], end="\t")# 如果牌⾯含有A 则添加不同点数1和11if (code_index + 1) == 1:current_player[0] += 1current_player[1] += 11# 如果牌⾯不含A 则添加相同点数else:current_player[0] += code_index + 1current_player[1] += code_index + 1# 如果两个点数⼀致则打印⼀个点数if current_player[0] == current_player[1]:print("点数为"+str(current_player[0])+"点")# 否则打印两个点数else:print("点数为"+str(current_player[0])+"点或"+str(current_player[1]))# 添加当前玩家点数player_point.append(current_player)# 返回所有玩家点数return player_point# 玩游戏def play_game():# 打印游戏规则print("-------21点游戏------")print("---A可看做1点或11点---")# 死循环⼀直进⾏游戏while True:# 初始化玩家数为0player_count = 0# 当玩家数⼩于等于1或⼤于5时继续询问while player_count <= 1 or player_count > 5:# 询问玩家数print("有多少位玩家?(2~5位)", end="")# 获取控制台输⼊的数字⽆验证输⼊若输⼊⾮数字程序直接报错player_count = int(input())# 初始化游戏返回玩家组玩家是否要牌乱序52张扑克player_group, player_isWant, poker = init(player_count)# 开始发牌先为每位玩家发两张牌循环玩家数for index in range(player_count):for i in range(2):# pop() 函数⽤于移除列表中的⼀个元素(默认最后⼀个元素)并且返回该元素的值。
c++21点游戏的代码和报告
数学与计算机学院课程设计说明书课程名称: 面向对象程序设计-课程设计课程代码: 8404101题目: 21点的扑克牌游戏年级/专业/班: 09/软件工程/1班学生姓名:学号: 312009*********开始时间:2011 年06 月13日完成时间:2011 年06月21 日课程设计成绩:指导教师签名:年月日目录1 引言 (1)1.1问题的提出 (1)1.2任务与分析 (1)2 程序的主要功能 (2)2.1新建用户功能 (2)2.2判断密码功能 (2)2.3判断进程功能 (2)2.4显示功能 (2)2.5获得牌的功能 (2)2.6初始化功能 (2)3 程序运行平台 (3)4 总体设计 (4)5 程序类的说明 (5)6 模块分析 (6)6.1新建用户模块 (6)6.2显示模块 (6)6.3判断密码模块 (8)6.4判断游戏进程模块 (10)6.5获得一张牌模块 (11)6.6初始化模块 (12)7 系统测试 (13)8 结论 (16)参考文献 (17)摘要随着计算机的普及,计算机游戏逐渐进入了这个时代,本次利用学到的c++编写了一个21点的扑克牌游戏,该游戏具有新建用户,判断牌等功能关键词:21点的扑克牌游戏;计算机;1 引言1.1 问题的提出设计一个21点的扑克牌游戏,玩家一共可以要5张牌,但如果牌的点数超过21,则暴了,自动出局;在不超过21点的情况下,玩家与庄家比牌的点数大小,大者为赢。
1.2任务与分析(1) 将所有的函数与相应的数据封装到类中。
(2) 程序中一共有13张扑克牌可以随机抽取,大于10的点数全部为半点:只需设计随机取下一张牌的成员函数时使用if语句判定牌的点数是否大于10,大于10的牌对其重新赋值为0.5即可。
(3) 要求庄家永远不会暴庄,即庄家可以查看下一张牌,若大于21点,则拒绝,当然,在游戏规则上不能泄露这点秘密:在函数中首先随机产生下一张牌,接着用条件语句判定原有点数与新牌的点数之和是否大于21点,然后决定是否取牌。
C语言21点纸牌游戏系统详细设计
C语言21点纸牌游戏系统详细设计主函数开键盘输产生随机键盘输输入H 输出统计选择是否循结图2.1 进入游戏后的游戏说明及规则2.2开始游戏图2.2 选择下注数目,然后随机发牌,只能见庄家一张牌,可以选择查看庄家隐藏的牌,此为游戏高级模式,开启后可选择想要的牌2.3作弊模式图2.4在作弊模式下取胜,可以接着要牌,但玩家的牌最多不能超过5张,取胜后会统计结果,询问是否继续游戏2.5非作弊模式图2.5 此情况为非作弊模式,不能见庄家的牌,只能知道结果,输掉游戏后统计结果,询问是否继续2.6退出游戏图2.6此为退出游戏,输入后自动关闭窗口3.源程序:#include<time.h>#include<stdio.h>#include<conio.h>#include<stdlib.h>void Wait_f(int);void Pause_f();/*暂停,按任意键继续*/int Random_f(long ,long );/*返回两个参数之间的随机数*/ void Replay_f(char *);/*询问是否重开一局*/void Hit_f(int *);/*发一张牌*/void Deal_f(int *,int *,int *,int *);/*双方各发两张牌*/nCpuTurns=0,nMoney=0,nBet;/* nPlayer--玩家手中全部牌的点数和,nPlayerTurns--玩家手中牌的数量 char chAnswer;char mmm;int a;system("cls");/* 执行系统命令"清屏" */Rules_f();printf("确认是否开始游戏:");scanf("%c",&chAnswer);if((chAnswer=='y')||(chAnswer=='Y')){nMoney=100;printf("\t\t\t");Pause_f();}else{return(0);return(0);}Bet_f(&nBet,&nMoney);/*接受下注的数目*/Deal_f(&nPlayer,&nCpu,&nPlayerTurns,&nCpuTurns);/*双方各发两张牌*/printf("想看庄家牌吗?");scanf("%c",&mmm);if((mmm=='y')||(mmm=='Y')){printf("%d\n",nnn);printf("您想要哪一张牌?");scanf("%d",&a);}system("cls");do{if((nPlayerTurns<6)&&(chAnswer=='h')) {printf("\n");if((mmm=='y')||(mmm=='Y'))Hit_f2(&nPlayer,a);else Hit_f(&nPlayer);/*为玩家发一张牌*/}}while((chAnswer=='h')||(chAnswer=='H'));for(;(nCpu<16)&&(nCpuTurns<6);nCpuTurns++)/*计算机要牌的条件*/ {printf("\n");printf("\n");printf("\t\t\t\t");return(0);}void Rules_f() /*这个函数显示游戏规则*/{printf("欢迎来到21点纸牌游戏\n");printf("这里有一些简单的规则:\n");printf("1:你的几张牌中只能有一个最大的牌。
C++课程设计---21点纸牌游戏程序
#include<iostream.h>#include<stdlib.h>#include<conio.h>#include<time.h>#include<iostream.h>#include<string.h>class Game{public:Game(){win=0,lose=0,draw=0,playerturns=0,cputurns=0,money=100,bet=0;player=0,cpu=0;char answer1[]="123456";strcpy(answer,answer1);char answer2[]="654321";strcpy(daan,answer2);};void rules();//显示规则void BET(); //下注void deal();//交易void run(Game &);//进行异常处理void hit1();//拿下一张牌void hit2();//确保庄家不会爆庄并且点数大于16void print();//打印出最后结果void results();//最后的胜利结果void check();//检查是否爆庄Game operator=(Game &d);//运算符重载void replay(char &ans);//是否进行新一轮的游戏void clean();//清屏void wait(int);void pause();int GetInt(int,int);int random(long,long);private:int playerturns,cputurns,money;int win,lose,draw,bet;float player,cpu;char answer[7];char daan[7];};//---------------------------------------------------------------------------------------void Game::wait(int milli){clock_t start;start=clock();while( ( clock()-start ) < milli );}//=========================================================void Game:: pause(){cout<<"Press Any Key To Continue"<<endl;getch();}//=========================================================int Game::GetInt(int L=0,int H=100){int ent;cout<<"Please Enter A Number Between "<<L<<" and "<<H<<endl; cin>>ent;while((ent<L)||(ent>H)){cout<<"Error"<<endl;cout<<"Value must be between "<<L<< " and "<<H<<endl; cin>>ent;}return(ent);}//==========================================================int Game::random(long hi,long lo)//随机抽牌{int ran;srand((unsigned)time(NULL));ran=rand()%(hi-(lo-1))+lo;return(ran);}//=============================================================void Game::rules(){cout<<"\t\t\t *********欢迎使用21点游戏软件*********"<<endl;cout<<endl;cout<<endl;cout<<"\t\t\t 游戏规则: "<<endl;cout<<endl;cout<<"\t\t\t ※①:每轮游戏你最多只可以有5张牌。
C++程序设计21点游戏
课程设计说明书
题
目 :“21 点”纸牌游戏
学生姓名:
学
号:
学
院:
班
级:
指导教师:
二〇一二年一月四日
大学课程设计(论文)任务书
课程名称: 面向对象的程序设计 学院:
班级:
学生姓名:
一、题目
“21 点”纸牌游戏
学号: 指导教师:
二、目的与意义
面向对象程序设计课程设计可以培养学生综合运用所学面向对象程序设计知识和技能分析 与解决实际问题的能力,以及严肃认真的科学态度和严谨求实的工作作风。
已在广泛的软件是非常重要的,可以节省大量的人力和物力。 (2) C++是一种面向对象的程序设计语言它使得程序的各个模块的独立性更
强,程序的可读性和可移植性更强,程序代码的结构更加合理,程序的扩充性更 强。这对于设计、编制和调试一些大型的软件尤为重要。
(3) C++集成环境不仅支持 C++程序的编译和调试,而且也支持 C 程序的编 译和调试。通常,C++程序环境 约定:当源程序文件的扩展名为 c.时,则为 C 程序;而当源程序文件的扩展名为 cpp.时,则为 C++程序。
人民邮电出版社.2006
[3] Walter Savitch. C++面向对象程序设计——基础、数据结构与编程思想.第 4 版.北京: 清华大学出版社.2003
[4]钱能.C++程序设计教程.第 2 版.北京:清华大学出版社.2005 [5]郑莉.C++语言程序设计案例教程.第 1 版.北京:清华大学出版社.2005 [6]韦朴,陈泰生. Visual C++通用范例开发金典.北京:电子工业出版社.2008
21点游戏实验报告
实验一21点游戏一、实验目的1.掌握使用Java语言进行结构化程序设计;2.熟悉Java基本语法,基本数据类型,各种运算符及表达式的使用,掌握运算符优先级,熟悉使用Java的选择语句,循环语句。
3.熟悉Eclipse开发环境,编写简单的Application程序,并编译和执行。
二、实验要求1.调试程序、编译,运行后得到正确的结果;2.写出实验报告,要求记录编译和执行Java程序当中的系统错误信息提示,并给出解决办法。
三、实验环境1.计算机一台;2.JDK、MyEclipse工具软件。
四、实验内容编写并运行21点游戏。
具有菜单形式的界面掌握Random类基本用法设计胜负判定算法五、实验步骤1.了解21点游戏的基本规则2.用0到53代表52张扑克牌3.完成洗牌发牌模块4.设计胜负判定算法六、实验结果源代码为:package youxi21dian;import java.util.Scanner;import java.util.Random;public class Dian21 {/*** @param args*/static int bb[]=new int[52];static String aa[]=new String[52];static Scanner s=new Scanner(System.in);static Random r=new Random();static int s1=0,s2=0,p=0;//同意发排,s1,s2表示甲方和乙方的最后点数public static void main(String[] args) {// TODO Auto-generated method stubfor(int i=0;i<52;i++)bb[i]=i%13+1;for(int i=0;i<13;i++)aa[i]="红桃"+(i+1);for(int i=13;i<26;i++)aa[i]="黑桃"+(i%13+1);for(int i=26;i<39;i++)aa[i]="方片"+(i%13+1);for(int i=39;i<52;i++)aa[i]="梅花"+(i%13+1);System.out.println("欢迎使用游戏21点!");System.out.println("请选择盘点方:0甲方,1 乙方!");int f=s.nextInt();if(f==0)System.out.println("您为:甲方;对方为:乙方!");else System.out.println("您为:乙方;对方为:甲方!");xipai();System.out.println("现在开始发牌!");int j=1,y=1;fapai(j,y);while(j==1||y==1){System.out.println("如果需要发牌请按1!若不需要请按0!");System.out.print("甲方请选择:");int a=s.nextInt();j=a;System.out.print(" 乙方请选择:");int b=s.nextInt();y=b;System.out.println("");fapai(j,y);}System.out.println("结果为:");result();}//洗牌public static void xipai(){int t;String l;for(int m=0;m<1000;m++){int i=r.nextInt(51);t=bb[i];bb[i]=bb[51-i];bb[51-i]=t;l=aa[i];aa[i]=aa[51-i];aa[51-i]=l;}}//发牌public static void fapai(int j,int y){if(j==1){System.out.print("甲方为: ");System.out.print(aa[p]);System.out.println(" "+"点数为:"+" "+bb[p]);s1=s1+bb[p++];}else System.out.println("甲方不需要发牌!");if(y==1){System.out.print("乙方为: ");System.out.print(aa[p]);System.out.println(" "+"点数为:"+" "+bb[p]);s2=s2+bb[p++];}else System.out.println("乙方不需要发牌!");}//结果public static int result(){System.out.print("甲方点数为: "+s1);System.out.println(" 乙方点数为: "+s2);if(s1>21&&s2>21){System.out.println("双方点数均超过21点,都被爆掉了!平局!");return 0;}if(s1>21&&s2<=21){System.out.println("甲方点数超过21点,被爆掉了!乙方胜!");return 0;}if(s2>21&&s1<=21){System.out.println("乙方点数超过21点,被爆掉了!甲方胜!");return 0;}if(s2>s1){System.out.println("乙方胜!");return 0;}else if(s2==s1){System.out.println("平局!");return 0;}else {System.out.println("甲方胜!");return 0;}}}结果为:欢迎使用游戏21点!请选择盘点方:0甲方,1 乙方!1您为:乙方;对方为:甲方!现在开始发牌!甲方为: 梅花13 点数为: 13乙方为: 梅花12 点数为: 12如果需要发牌请按1!若不需要请按0!甲方请选择:1乙方请选择:1甲方为: 梅花11 点数为: 11乙方为: 红桃4 点数为: 4如果需要发牌请按1!若不需要请按0!甲方请选择:0乙方请选择:0甲方不需要发牌!乙方不需要发牌!结果为:甲方点数为: 24 乙方点数为: 16甲方点数超过21点,被爆掉了!乙方胜!。
c#小游戏21点代码和界面
public partial class Form1 : Form{public int a;public int b;public int i;public int[] ab = new int[12];//数组ab存放临时的牌的图片号public int zhuangnumber;//用于存放庄家点数public int gamernumber;//用于存放游戏者点数public PictureBox[] ptb = new PictureBox[12];public Form1(){InitializeComponent();}//生成牌与点数private void First(out int a, out int b, int q){Random rd = new Random();a = rd.Next(0, 51);if (a >= 0 && a <= 3){b = 2;}else if (a >= 4 && a <= 7)b = 3;}else if (a >= 8 && a <= 11) {b = 4;}else if (a >= 12 && a <= 15) {b = 5;}else if (a >= 16 && a <= 19) {b = 6;}else if (a >= 20 && a <= 23) {b = 7;}else if (a >= 24 && a <= 27) {b = 8;}else if (a >= 28 && a <= 31) {b = 9;}else if (a >= 32 && a <= 47) {b = 10;}else if (a >= 48 && a <= 51) {if (q >= 0 && q <= 21) {b = 10;}elseb = 1;}else{b = 0;Console.Read();}//用递归算法随即生成之前未出现的牌public void Bijiao(out int a, out int b, int q, int[] abc) {int i;Random rd = new Random();a = rd.Next(0, 51);if (a >= 0 && a <= 3){b = 2;}else if (a >= 4 && a <= 7){b = 3;}else if (a >= 8 && a <= 11){b = 4;}else if (a >= 12 && a <= 15){b = 5;}else if (a >= 16 && a <= 19){b = 6;}else if (a >= 20 && a <= 23){b = 7;}else if (a >= 24 && a <= 27){b = 8;}else if (a >= 28 && a <= 31){b = 9;}else if (a >= 32 && a <= 47){b = 10;else if (a >= 48 && a <= 51){if (q >= 0 && q <= 21){b = 10;}elseb = 1;}else{b = 0;Console.Read();}for (i = 0; i < 52; i++){if (abc[i] == a)Bijiao(out a, out b, q,abc);elsebreak;}}//不要牌后比较出赢家并把庄家隐藏的牌显现private void buttonResult_Click(object sender, EventArgs e){if (zhuangnumber > gamernumber){for (i = 1; i < 6; i++){if (ab[i] != 100)this.ptb[i].Image = this.imageList1.Images[ab[i]];}bel2.Text = zhuangnumber.ToString();MessageBox.Show("庄家赢了!开始下一局!");}else if (zhuangnumber == gamernumber){for (i = 1; i < 6; i++){if(ab[i]!=100)this.ptb[i].Image = this.imageList1.Images[ab[i]];}bel2.Text = zhuangnumber.ToString();MessageBox.Show("庄家赢了!开始下一局!");}else{for (i = 1; i < 6; i++){if (ab[i] != 100)this.ptb[i].Image = this.imageList1.Images[ab[i]];}bel2.Text = zhuangnumber.ToString();MessageBox.Show("你赢了!开始下一局!");}}private void结束ToolStripMenuItem_Click(object sender, EventArgs e){Application.Exit();}//游戏规则在第二个Form上private void游戏规则ToolStripMenuItem_Click(object sender, EventArgs e){Form2 myform = new Form2();myform.Show();}//开始在panel上添加PictureBox并设置其属性,生成四张牌,各两张(庄家有一张隐藏)private void开始ToolStripMenuItem_Click_1(object sender, EventArgs e){for (i = 0; i < 12; i++){this.ptb[i] = new PictureBox();this.ptb[i].SizeMode = PictureBoxSizeMode.CenterImage;this.ab[i] = new int();this.ptb[i].Visible = true;ab[i] = 100;//初始化数组abthis.ptb[i].Image = this.imageList1.Images[52];//初始化PicturBox 的图片 }for (i = 0; i < 6; i++){this.panelT.Controls.Add(this.ptb[i]);this.ptb[i].Width = 85;this.ptb[i].Height = 120;this.ptb[i].Top = 11;this.ptb[i].Left = 17 + 85 * i + 15 * (i + 1);}for (i = 6; i < 12; i++){this.panelB.Controls.Add(this.ptb[i]);this.ptb[i].Width = 85;this.ptb[i].Height = 120;this.ptb[i].Top = 11;this.ptb[i].Left = 17 + 85 * (i - 6) + 15 * (i - 5); }bel2.Visible = true;ble4.Visible = true;First(out a, out b, zhuangnumber);zhuangnumber = b;this.ptb[0].Image = this.imageList1.Images[a];ab[0] = a;First(out a, out b, gamernumber);if (ab[0] == a){while (ab[0] == a){First(out a, out b, gamernumber);}gamernumber = b;this.ptb[6].Image = this.imageList1.Images[a];ab[6] = a;}else{gamernumber = b;this.ptb[6].Image = this.imageList1.Images[a];ab[6] = a;}First(out a, out b, zhuangnumber);if (ab[0] == a || ab[1] == a){while (ab[0] == a || ab[1] == a){First(out a, out b, zhuangnumber);}zhuangnumber = zhuangnumber + b;ab[1] = a;}else{zhuangnumber = zhuangnumber + b;ab[1] = a;}bel2.Text = "未知!";First(out a, out b, gamernumber);if (ab[0] == a || ab[1] == a || ab[2] == a){while (ab[0] == a || ab[1] == a || ab[6] == a){First(out a, out b, gamernumber);}gamernumber = gamernumber + b;this.ptb[7].Image = this.imageList1.Images[a];ab[7] = a;}else{gamernumber = gamernumber + b;this.ptb[7].Image = this.imageList1.Images[a];ab[7] = a;}ble4.Text = gamernumber.ToString();}//要的牌必须是未出现的牌,接着检测是否有点数爆了private void buttoninfo_Click(object sender, EventArgs e) {Bijiao(out a,out b,zhuangnumber,ab);for (i = 1; i < 5; i++){if (ab[i] != 100 && ab[i + 1] == 100){ab[i + 1] = a;break;}}zhuangnumber = zhuangnumber + b;bel2.Text = "未知!";Bijiao(out a, out b, gamernumber, ab);for (i = 7; i < 11; i++){if (ab[i] != 100 && ab[i + 1] == 100){ab[i+1] = a;this.ptb[i+1 ].Image = this.imageList1.Images[ab[i+1]];break;}}gamernumber = gamernumber + b;ble4.Text = gamernumber.ToString();if (zhuangnumber > 21 && gamernumber > 21){for (i = 1; i < 6; i++){if (ab[i] != 100)this.ptb[i].Image = this.imageList1.Images[ab[i]];}bel2.Text = zhuangnumber.ToString();MessageBox.Show("平局!开始下一局!");}else if (zhuangnumber > 21){for (i = 1; i < 6; i++){if (ab[i] != 100)this.ptb[i].Image = this.imageList1.Images[ab[i]];}bel2.Text = zhuangnumber.ToString();MessageBox.Show("庄家爆了!你赢了!开始下一局!");}else if (gamernumber > 21){for (i = 1; i < 6; i++){if (ab[i] != 100)this.ptb[i].Image = this.imageList1.Images[ab[i]];}bel2.Text = zhuangnumber.ToString();MessageBox.Show("你爆了!庄家赢了!开始下一局!");}}//洗牌,界面为初始界面private void button1_Click(object sender, EventArgs e){for (i = 0; i < 12; i++){this.ptb[i].Visible = false; }bel2.Visible = false;ble4.Visible = false;}}。
python实现21点小游戏
python实现21点⼩游戏⽤python实现21点⼩游戏,供⼤家参考,具体内容如下from random import shuffleimport randomimport numpy as npfrom sys import exit# 初始化扑克牌playing_cards = {"⿊桃A": 1, "⿊桃2": 2, "⿊桃3": 3, "⿊桃4": 4, "⿊桃5": 5, "⿊桃6": 6, "⿊桃7": 7, "⿊桃8": 8, "⿊桃9": 9, "⿊桃10": 10, "⿊桃J": 10, "⿊桃Q": 10, "⿊桃K": 10,"红桃A": 1, "红桃2": 2, "红桃3": 3, "红桃4": 4, "红桃5": 5, "红桃6": 6, "红桃7": 7, "红桃8": 8, "红桃9": 9, "红桃10": 10, "红桃J": 10, "红桃Q": 10, "红桃K": 10,"梅花A": 1, "梅花2": 2, "梅花3": 3, "梅花4": 4, "梅花5": 5, "梅花6": 6, "梅花7": 7, "梅花8": 8, "梅花9": 9, "梅花10": 10, "梅花J": 10, "梅花Q": 10, "梅花K": 10,"⽅块A": 1, "⽅块2": 2, "⽅块3": 3, "⽅块4": 4, "⽅块5": 5, "⽅块6": 6, "⽅块7": 7, "⽅块8": 8, "⽅块9": 9, "⽅块10": 10, "⽅块J": 10, "⽅块Q": 10, "⽅块K": 10}# 扑克牌⾯poker_name = list(playing_cards.keys())# 扑克牌的数量poker_count = 1poker_list = poker_count*poker_name# ⽤于判断⼿中的牌是否有A,再根据牌⾯判断A是否取值1还是11four_a = {'⿊桃A', '红桃A', '梅花A', '⽅块A'}# 计分器total_score = np.array([0, 0])# 记录回合数game_round = 1def random_cards(poker_name_list):"""定义洗牌函数:重新对牌进⾏随机排列"""shuffle(poker_name_list)def score_count(hand_poker):"""计算⼿中牌的分数:param hand_poker:⼀个含有牌名的列表:return: ⼿中牌的分数poker_score"""# 声明⼀个变量,记录牌的总分数poker_score = 0# 标记:判断是否有A的标记,默认没有have_a = False# 计算⼿中牌的分数for k in hand_poker:poker_score += playing_cards[k]# 判断⼿中的牌是否含有A,再根据A的规则进⾏分数的计算for i in hand_poker:if i in four_a:have_a = Truebreakelse:continueif have_a:if poker_score + 10 <= 21:poker_score = poker_score + 10return poker_scoredef who_win(your_score, pc_score):"""判断游戏的胜负:param your_score: 玩家分数:param pc_score: 电脑分数:return: 胜负的数组"""if your_score > 21 and pc_score > 21:print('平局')return np.array([0, 0])elif your_score > 21 and pc_score <= 21:print('对不起,玩家输了')return np.array([0, 1])elif your_score <= 21 and pc_score > 21:print('恭喜!!玩家胜利了')return np.array([1, 0])elif your_score <= 21 and pc_score <= 21:if your_score > pc_score:print('恭喜!!玩家胜利了')return np.array([1, 0])elif your_score < pc_score:print('对不起,玩家输了')return np.array([0, 1])else:print('平局!!')return np.array([0, 0])def if_get_next_poker():"""是否继续要牌"""if_continue = input("是否继续要下⼀张牌?(Y/N)>>>>:")if if_continue.upper() == "Y":return get_one_poker()elif if_continue.upper() == "N":print('玩家停⽌叫牌')return Falseelse:print("输⼊有误,请重新输⼊")return if_get_next_poker()def get_one_poker():"""发牌函数:随机将poker_list⾥的牌取出⼀张:return:"""return poker_list.pop(random.randint(0, len(poker_list)-1))def continue_or_quit():"""⼀轮游戏结束后,询问玩家是否进⾏下⼀轮"""if_next_round = input("是否进⾏下⼀轮游戏(Y/N)>>>>:")if if_next_round.upper() == 'Y':# 判断扑克牌是否玩的了下⼀轮if len(poker_list) <= 15:print('对不起,剩余牌数不⾜,⽆法进⾏下⼀轮,游戏结束。
C++课程设计---21点纸牌游戏程序
#include<iostream.h>#include<stdlib.h>#include<conio.h>#include<time.h>#include<iostream.h>#include<string.h>class Game{public:Game(){win=0,lose=0,draw=0,playerturns=0,cputurns=0,money=100,bet=0;player=0,cpu=0;char answer1[]="123456";strcpy(answer,answer1);char answer2[]="654321";strcpy(daan,answer2);};void rules();//显示规则void BET(); //下注void deal();//交易void run(Game &);//进行异常处理void hit1();//拿下一张牌void hit2();//确保庄家不会爆庄并且点数大于16void print();//打印出最后结果void results();//最后的胜利结果void check();//检查是否爆庄Game operator=(Game &d);//运算符重载void replay(char &ans);//是否进行新一轮的游戏void clean();//清屏void wait(int);void pause();int GetInt(int,int);int random(long,long);private:int playerturns,cputurns,money;int win,lose,draw,bet;float player,cpu;char answer[7];char daan[7];};//---------------------------------------------------------------------------------------void Game::wait(int milli){clock_t start;start=clock();while( ( clock()-start ) < milli );}//========================================================= void Game:: pause(){cout<<"Press Any Key To Continue"<<endl;getch();}//=========================================================int Game::GetInt(int L=0,int H=100){int ent;cout<<"Please Enter A Number Between "<<L<<" and "<<H<<endl;cin>>ent;while((ent<L)||(ent>H)){cout<<"Error"<<endl;cout<<"Value must be between "<<L<< " and "<<H<<endl;cin>>ent;}return(ent);}//==========================================================int Game::random(long hi,long lo)//随机抽牌{int ran;srand((unsigned)time(NULL));ran=rand()%(hi-(lo-1))+lo;return(ran);}//============================================================= void Game::rules(){cout<<"\t\t\t *********欢迎使用21点游戏软件*********"<<endl;cout<<endl;cout<<endl;cout<<"\t\t\t 游戏规则:"<<endl;cout<<endl;cout<<"\t\t\t ※①:每轮游戏你最多只可以有5张牌。
21点源代码
#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <time.h>#include <windows.h>//二维数组:第一行存储牌的点数,第二行存储牌的符号int cpu_card[2][5]={0},cpu_count=0,cpu_trun; //cpu_count表示电脑牌数,cpu_turn表示电脑是否要牌的状态int play_card[2][5]={0},play_count=0,play_trun; //play_count表示玩家牌数,play_turn表示玩家是否要牌的状态int win=0,lose=0,draw=0; //win表示赢的局数,lose表示输的局数,draw表示平的局数int cpuds(); //计算电脑总点数int playerds(); //计算玩家总点数void rule() //游戏规则{printf("*********欢迎进入21点游戏世界!*********\n");printf("* 基本游戏规则:*\n");printf("* 游戏纸牌不包含大小鬼*\n");printf("* 开始游戏每人发一张牌*\n");printf("* 玩家最多可以要五张牌*\n");printf("* 谁先到21点或最接近21点算谁赢*\n");printf("* 点数相同或都超过21点时算平局*\n");printf("* 祝您好运!*\n");printf("**************************CJY作*********\n");printf("(1)新游戏\n");printf("(0)离开游戏\n");printf("(2)退出\n");}void result() //最终结局{printf("您胜了%d次\n",win);printf("您输了%d次\n",lose);printf("您平了%d次\n",draw);printf("\n");}int random(int n){int nn;srand((unsigned)time(NULL)+rand()); //设置随机数种子nn=rand()%n;return nn;}void cpucard(int less) //电脑的纸牌{for(int i=0;i<cpu_count;i++)printf("┏┓ ");printf("\n");if(less==1){printf(" * * ");for(int i=1;i<cpu_count;i++){printf(" %c",cpu_card[1][i]);if(cpu_card[0][i]<10&&cpu_card[0][i]!=1)printf(" %d ",cpu_card[0][i]);if(cpu_card[0][i]==10)printf("10 ");if(cpu_card[0][i]==11)printf(" J ");if(cpu_card[0][i]==12)printf(" Q ");if(cpu_card[0][i]==13)printf(" K ");if(cpu_card[0][i]==1)printf(" A");}}else{for(int i=0;i<cpu_count;i++){printf(" %c",cpu_card[1][i]);if(cpu_card[0][i]<10&&cpu_card[0][i]!=1)printf(" %d ",cpu_card[0][i]);if(cpu_card[0][i]==10)printf("10 ");if(cpu_card[0][i]==11)printf(" J ");if(cpu_card[0][i]==12)printf(" Q ");if(cpu_card[0][i]==13)printf(" K ");if(cpu_card[0][i]==1)printf(" A");}}printf("\n");for(int i=0;i<cpu_count;i++)printf("┗┛ ");printf("\n");}void playercard() //玩家的纸牌{for(int i=0;i<play_count;i++)printf("┏┓ ");printf("\n");for(int i=0;i<play_count;i++){printf(" %c",play_card[1][i]);if(play_card[0][i]<10&&play_card[0][i]!=1)printf(" %d ",play_card[0][i]); if(play_card[0][i]==10)printf("10 ");if(play_card[0][i]==11)printf(" J ");if(play_card[0][i]==12)printf(" Q ");if(play_card[0][i]==13)printf(" K ");if(play_card[0][i]==1)printf(" A");}printf("\n");for(int i=0;i<play_count;i++)printf("┗┛ ");printf("\n");}int cpuds(){int s=0;for(int i=0;i<cpu_count;i++){if(cpu_card[0][i]<10)s+=cpu_card[0][i];else s+=10;}return s;}int playerds(){int s=0;for(int i=0;i<play_count;i++){if(play_card[0][i]<10)s+=play_card[0][i];else s+=10;}return s;}int minus(int n){if(n>10)return 10;return n;}void print() //显示全部纸牌{printf("***********************************\n");printf("您的牌点分别是:\n");playercard();printf("电脑的牌点分别是:\n");cpucard(1);printf("您的牌得点数和是:%d\n",playerds());printf("电脑已知的牌得点数和是:%d\n",cpuds()-minus(cpu_card[0][0])); //减去第一张牌的点数(针对电脑而言)printf("***********************************\n");}void print_end() //显示每局的最终结果{printf("***********************************\n");printf("您的牌点分别是:\n");playercard();printf("电脑的牌点分别是:\n");cpucard(0);printf("您的牌的点数和是:%d\n",playerds());printf("电脑的牌的点数和是:%d\n",cpuds());printf("***********************************\n");}void judge_end() //判断输赢{system ("cls");print_end();if(playerds()<=21&&cpuds()<=21&&playerds()==cpuds()){draw++;printf("双方一样,平局!\n");}if(playerds()>21&&cpuds()>21){draw++;printf("双方都爆了,平局!\n");}if(playerds()<=21&&cpuds()<=21&&playerds()>cpuds()){win++;printf("您获胜了!\n");}if(playerds()<=21&&cpuds()>21){win++;printf("电脑爆了,您获胜了!\n");}if(playerds()<=21&&cpuds()<=21&&playerds()<cpuds()){lose++;printf("您输了,电脑获胜了!\n");}if(playerds()>21&&cpuds()<=21){lose++;printf("您爆了,电脑获胜了!\n");}}void game() //开始游戏{int ss;cpu_count=1;play_count=1;cpu_card[0][0]=random(13)+1; //随即获取纸牌数值cpu_card[1][0]=random(4)+3; //随即获取纸牌符号play_card[0][0]=random(13)+1;play_card[1][0]=random(4)+3;while(1){system ("cls");print();if(playerds()>21){printf("点数超过21,自动弃牌!\n");Sleep(1200);ss=0;} else {printf("您是否继续要牌?(1/0)");Sleep(1000);scanf("%d",&ss);}if(ss==1&&play_count==5){printf("\n对不起,您已经要了五张牌了!");ss=0;}if(ss==1) play_trun=1;else play_trun=0;if(cpuds()<16&&cpu_count<=5) cpu_trun=1;else cpu_trun=0;if(cpu_trun==0&&play_trun==0){judge_end();return;}if(cpu_trun==1){cpu_card[0][cpu_count]=random(13)+1;cpu_card[1][cpu_count]=random(4)+3;cpu_count++;}if(play_trun==1){play_card[0][play_count]=random(13)+1;play_card[1][play_count]=random(4)+3;play_count++;}}}main(){int ss;while(1){system ("cls");rule();printf("请输入:");scanf("%d",&ss);if(ss==0){system ("cls");printf("您结束了游戏,最后您的状态是:\n");result();printf(" \n适度游戏益脑沉迷游戏伤身\n");printf("按任意键继续...");getch();}if(ss==1){system ("cls");game();printf("\n按任意键继续.........");getch();system ("cls");}if(ss==2) {exit(0);}}}。
21点游戏源代码
printf("你愿意玩一局吗?(Y or N)\n");
scanf("%c",&chanswer);
if((chanswer=='y')||(chanswer=='Y'))
{
pmoney=100;
}
else
printf("\n\t谢谢使用!再见!\n");
*pturns=2;
*cturns=2;
playercard1=random(13,1);
delay(150);
cpucard1=random(13,1);
delay(150);
playercard2=random(13,1);
delay(150);
printf(" ***********如果你赢了可以获得两倍的你下注的资金*************\n");
printf(" ****************牌数总和在16点以后就不再发牌****************\n");
}
void pause()// 暂停函数
{
printf("\n 恭喜你!你赢了啊!\n");
++*pwin;
*pmoney=*pmoney+*pbet+*pbet1;
}
else if((player>21)&&(cpu>21))
{
printf("\n 平局!很可惜啊,你什么也没捞!\n");
++*pdraw;
21点游戏程序代码有特殊情况
Public Class GameInterfaceDim p(10), c(10) As IntegerDim t, i, CScore, PScore, m As IntegerPrivate Sub GameInterface_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadMe.Top = 45Me.Left = 80Randomize()Timer1.Interval = 1000End SubPrivate Sub btnPlay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPlay.ClickTryDisplayReset()m = 10lblTime.Text = mIf m = 10 ThenTimer1.Enabled = TrueEnd Ifp(1) = Int(Rnd() * 52 + 1)Dot = Int(Rnd() * 52 + 1)Loop While t = p(1)c(1) = tDot = Int(Rnd() * 52 + 1)Loop While t = p(1) Or t = c(1)p(2) = tDot = Int(Rnd() * 52 + 1)Loop While t = p(1) Or t = c(1) Or t = p(2)c(2) = tptbP1.Image = Image.FromFile("Images\" & p(1) & ".jpg")ptbC1.Image = Image.FromFile("Images\" & c(1) & ".jpg")PtbP2.Image = Image.FromFile("Images\" & p(2) & ".jpg")ptbC2.Image = Image.FromFile("Images\back.jpg")Catch ex As ExceptionMsgBox("Error")End TryEnd SubPrivate Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.TicklblTime.Text = lblTime.Text - 1If lblTime.Text = 0 ThenDisplayData()End IfEnd SubPrivate Sub btnCall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCall.ClickTryIf ptbP3.Image Is Nothing ThenDot = Int(Rnd() * 52 + 1)Loop While t = p(1) Or t = c(1) Or t = p(2) Or t = c(2)p(3) = tptbP3.Image = Image.FromFile("Images\" & p(3) & ".jpg")Add()If PScore >= 22 ThenMsgBox("Yours points beyond the blackjack, you lose!")DisplayData()End IflblTime.Text = 10ElseIf ptbP4.Image Is Nothing ThenDot = Int(Rnd() * 52 + 1)Loop While t = p(1) Or t = c(1) Or t = p(2) Or t = c(2) Or t = p(3)p(4) = tptbP4.Image = Image.FromFile("Images\" & p(4) & ".jpg")Add()If PScore >= 22 ThenMsgBox("Yours points beyond the blackjack, you lose!")DisplayData()End IflblTime.Text = 10ElseIf ptbP5.Image Is Nothing ThenDot = Int(Rnd() * 52 + 1)Loop While t = p(1) Or t = c(1) Or t = p(2) Or t = c(2) Or t = p(3) Or t = p(4) p(5) = tptbP5.Image = Image.FromFile("Images\" & p(5) & ".jpg")lblTime.Text = 10Add()If PScore >= 22 ThenMsgBox("Yours points beyond the blackjack, you lose!")DisplayData()End IfElseIf ptbP6.Image Is Nothing ThenDot = Int(Rnd() * 52 + 1)Loop While t = p(1) Or t = c(1) Or t = p(2) Or t = c(2) Or t = p(3) Or t = p(4) Or t = p(5)p(6) = tptbP6.Image = Image.FromFile("Images\" & p(6) & ".jpg")lblTime.Text = 10Add()If PScore >= 22 ThenMsgBox("Yours points beyond the blackjack, you lose!")DisplayData()End IfEnd IfCatch ex As ExceptionMsgBox("Error")End TryEnd SubPrivate Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.ClickDisplayData()End SubPrivate Sub Calculate()Add()If PScore >= 22 ThenElseIf CScore < 17 ThenDot = Int(Rnd() * 52 + 1)Loop While t = p(1) Or t = c(1) Or t = p(2) Or t = c(2)c(3) = tptbC3.Image = Image.FromFile("Images\back.jpg")Add()If CScore < 17 ThenDot = Int(Rnd() * 52 + 1)Loop While t = p(1) Or t = c(1) Or t = p(2) Or t = c(2) Or t = c(3)c(4) = tptbC4.Image = Image.FromFile("Images\back.jpg")Add()If CScore < 17 ThenDot = Int(Rnd() * 52 + 1)Loop While t = p(1) Or t = c(1) Or t = p(2) Or t = c(2) Or t = c(3) Or t = c(4)c(5) = tptbC5.Image = Image.FromFile("Images\back.jpg")Add()End IfEnd IfEnd IfEnd IfEnd SuPrivate Sub ShowC()PScore = 0CScore = 0For i = 1 To 10If p(i) <= 10 ThenMe.p(i) = p(i)ElseIf p(i) >= 14 And p(i) <= 23 ThenMe.p(i) = p(i) - 13ElseIf p(i) >= 27 And p(i) <= 36 ThenMe.p(i) = p(i) - 26ElseIf p(i) >= 40 And p(i) <= 49 ThenMe.p(i) = p(i) - 39ElseMe.p(i) = 10End IfNextFor i = 1 To 10If c(i) <= 10 ThenMe.c(i) = c(i)ElseIf c(i) >= 14 And c(i) <= 23 ThenMe.c(i) = c(i) - 13ElseIf c(i) >= 27 And c(i) <= 36 ThenMe.c(i) = c(i) - 26ElseIf c(i) >= 40 And c(i) <= 49 ThenMe.c(i) = c(i) - 39ElseMe.c(i) = 10End IfNextEnd SubPrivate Sub DisplayResult()TryIf PScore <= 21 And CScore <= 21 ThenIf PScore > CScore ThenlblResult.Text = "Congratulations, you win!"ElselblResult.Text = "Sorry, you lost!"End IfElseIf PScore = CScore ThenlblResult.Text = "Sorry, you lost!"ElseIf CScore >= 22 And PScore <= 21 ThenlblResult.Text = "Congratulations, you win!"ElselblResult.Text = "Sorry, you lost!"End IfCatch ex As ExceptionMsgBox("Error")End TryEnd SubPrivate Sub DisplayData()TryCalculate()lblPScore.Text = PScorelblCScore.Text = CScoreptbC2.Image = Image.FromFile("Images\" & c(2) & ".jpg")lblResult.Visible = TrueTimer1.Enabled = FalseDisplayResult()btnPlay.Enabled = TruelblPScore.Visible = TruelblCScore.Visible = TruebtnCall.Enabled = FalsebtnStop.Enabled = FalseIf ptbC3.Image Is Nothing ThenElseptbC3.Image = Image.FromFile("Images\" & c(3) & ".jpg") End IfIf ptbC4.Image Is Nothing ThenElseptbC4.Image = Image.FromFile("Images\" & c(4) & ".jpg") End IfIf ptbC5.Image Is Nothing ThenElseptbC5.Image = Image.FromFile("Images\" & c(5) & ".jpg") End IfCatch ex As ExceptionMsgBox("Error")End TryEnd SubPrivate Sub DisplayReset()TrybtnCall.Enabled = TruebtnStop.Enabled = TrueTimer1.Enabled = TruebtnPlay.Enabled = FalselblCScore.Text = ""lblPScore.Text = ""lblResult.Text = ""ptbP3.Image = Nothingp(3) = 0ptbP4.Image = Nothingp(4) = 0ptbP5.Image = Nothingp(5) = 0ptbP6.Image = Nothingp(6) = 0ptbC3.Image = Nothingc(3) = 0ptbC4.Image = Nothingc(4) = 0ptbC5.Image = Nothingc(5) = 0Catch ex As ExceptionMsgBox("Error")End TryEnd SubPrivate Sub btnHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHelp.ClickMsgBox("If your points is 10 + 1 or 1 + 10, points you are 21. So you met in both cases, if you don't have to going to the next card.")End SubPrivate Sub Add()ShowC()For i = 0 To 10If PScore = 11 ThenIf Me.p(1) = 10 And Me.p(2) = 1 ThenIf ptbP3.Image Is Nothing ThenPScore = 21End IfEnd IfIf Me.p(1) = 1 And Me.p(2) = 10 ThenIf ptbP3.Image Is Nothing ThenPScore = 21End IfEnd IfEnd IfIf CScore = 11 ThenIf Me.c(1) = 10 And Me.c(2) = 1 ThenIf ptbP3.Image Is Nothing ThenCScore = 21End IfEnd IfIf Me.c(1) = 1 And Me.c(2) = 10 ThenIf ptbP3.Image Is Nothing ThenCScore = 21End IfEnd IfEnd IfPScore += p(i)CScore += c(i)NextEnd SubPrivate Sub btnRule_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRule.ClickMsgBox("Rules:" & vbCrLf & " The game role is computer and the player, respectively. Players play with computer, the computer is a banker. Start , each 2 CARDS. Players according to their own situtaion decided to brand or not.Loses more than 21 points. No more than 21 points,than the size od porins is the winner. When points are at the same time,the banker wins.") End SubEnd Class。
21点程序源代码
game.super(); break;
default:
cout<<"选择错误,程序退出!"<<endl;
}
return(0);
}
void CCard::setmoney(int a)
{
money=a;
}
//--------------------------------------------------------------------------------
{
do{
cout<<"你输入的字母错误,请从新输入."<<endl;
cin>>ans;
}while((ans!='H'&&ans!='h'&&ans!='s'&&ans!='S'));
}
if((ans=='h')||(ans=='H'))
//fuctions.
class CCard {
private:
float player; //玩家点数
float cpu; //电脑点数
int win; //赢的次数
game.deal(player,cpu,playerturns,cputurns); //为计算机和玩家个发两张牌
do{
cout<<"\n你想继续要牌还是不再要牌?h/s:"; //询问玩家是否要牌
cin>>ans;
21点游戏代码
21点游戏代码.txt举得起放得下叫举重,举得起放不下叫负重。
头要有勇气,抬头要有底气。
学习要加,骄傲要减,机会要乘,懒惰要除。
人生三难题:思,相思,单相思。
#include <stdio.h>#include <tchar.h>#include <stdlib.h>#include <time.h>#include"string.h"#include<iostream>using namespace std;///////////////////////////////////////////////////////////class Card{private:char m_type;int m_num;public:void card(char a,int b){m_type=a,m_num=b;}int outnum(){return m_num;}int GetText();};class Poker{private:int count;Card card[54];public:Poker();void Xipai();int Fapai();int sum(int,int,int);Card *getcard();};///////////////////////////////////////////////////Card *h;int get(int max,int min);// TODO: reference additional headers your program requires here///////////////////////////////////////////class Player{public:Card *card[20];int count;char name[10];int score;Player(){count=score=0;for(int i=0;i<20;i++)card[i]=NULL;}int showpoint();void showpoker();void reset();};class Newgame{private:Poker *poker;Player *player[5];int num,n;char boss[10],a[10];public:Newgame();void login();void begin();char *victory();bool callpoker(Player &);void show();};////////////////////////void Newgame::show(){for(int f=0;f<54;f++)poker->Fapai();}/////////////////////////////////int get(int max,int min){int n=rand();n=n%(max-min+1)+min;return n;}int Card::GetText(){if((1==m_num)&&(m_type=='K')){ printf("′èæ? ");return 1;}if((0==m_num)&&(m_type=='K')){ printf("D?æ? ");return 1;} int k=m_num%13;switch(k){case 1:{if(m_type=='H') cout<<"oååçA ";if(m_type=='C') cout<<"???¨A ";if(m_type=='D') cout<<"???ãA ";if(m_type=='S') cout<<"oëåçA ";return 1;}case 11:{if(m_type=='H'){ cout<<"oååçJ "; return 1;}if(m_type=='C'){ cout<<"???¨J "; return 1;}if(m_type=='D'){ cout<<"???ãJ "; return 1;}if(m_type=='S'){ cout<<"oëåçJ "; return 1;}}case 12:{if(m_type=='H'){ cout<<"oååçQ "; return 1;}if(m_type=='C'){ cout<<"???¨Q "; return 1;}if(m_type=='D'){ cout<<"???ãQ "; return 1;}if(m_type=='S'){ cout<<"oëåçQ "; return 1;}}case 0:{if(m_type='H'){ cout<<"oååçK "; return 1;}if(m_type=='C'){ cout<<"???¨K "; return 1;}if(m_type=='D'){ cout<<"???ãK "; return 1;}if(m_type=='S'){ cout<<"oëåçK "; return 1;}}return 1;}if(m_num<=10&&m_num>=2){if(m_type=='H'){ cout<<"oååç"<<m_num<<" "; return 1;}if(m_type=='C'){ cout<<"???¨"<<m_num<<" "; return 1;}if(m_type=='D'){ cout<<"???ã"<<m_num<<" "; return 1;}if(m_type=='S'){ cout<<"oëåç"<<m_num<<" "; return 1;} }return 1;}Poker::Poker(){count=54;for(int i=0;i<13;i++)card[i].card('H',(i+1));for(i=13;i<26;i++)card[i].card('C',((i%13)+1));for(i=26;i<39;i++)card[i].card('D',((i%13)+1)); for(i=39;i<52;i++)card[i].card('S',(i%13)+1);card[52].card('K',1);card[53].card('K',0);}void Poker::Xipai(){count=54;for(int k=0;k<54;k++){int m=get(54,1)%54;Card r;r=card[k];card[k]=card[m];card[m]=r;}}int Poker::Fapai(){if(count<=54&&count>=1){card[54-count].GetText();count--;}elsecout<<"??ç??-?¢æä!"<<endl;return count;}Card *Poker::getcard(void){if(count<=54&&count>0){h=&card[54-count];count--;return h;}elsecout<<"??ç??-?¢æä!"<<endl; return NULL;}int Poker::sum(int a,int b,int c) {return card[a].outnum()+card[b].outnum()+card[c].outnum();}///////////////////////////////////////////////////Newgame::Newgame(){poker=new Poker;login();num=n+1;player[0]=new Player;strcpy(player[0]->name,a);for(int i=1;i<=n;i++){player[i]=new Player;sprintf(player[i]->name,"Computer%d",i);}for(i=num;i<5;i++)player[i]=NULL;}void Newgame::login(){system("COLOR 1D");cout<<"21μ?è???...."<<endl;cout<<"??ä?â???μ???×?£o"<<endl;cin>>a;cout<<"????æ??àãê??μ???ç??eè???£?(1~4??£?"<<endl;cin>>n;while(n<1||n>4){cout<<"ä?â?3?′æ£?????ä?â?ç???1~4μ?äy×?£?ç?±??aä?è???£?"<<endl;cin>>n;}}bool Newgame::callpoker(Player &t){if(strcmp(,player[0]->name)!=0){if(t.showpoint()<11||(t.showpoint()>10&&get(15,1)<=(21-(t.showpoint() ))&&t.showpoint()<=21)) {t.card[t.count]=poker->getcard();cout<<<<"×¥á?ç?????£?"<<endl;t.count++;return 1;}else return 0;}else{if(t.showpoint()>=21) return 0;else{cout<<"?????åD?×¥???e£??????ëμ?μ?äy?a£o"<<t.showpoint()<<" Y or N"<<endl;char a;cin>>a;while(a!='y'&&a!='Y'&&a!='N'&&a!='n'){cout<<"?????ê′?â?â?ä?â?ä???3?′æ?(N or Y)"<<endl;cin>>a;}if(a=='Y'||a=='y'){t.card[t.count]=poker->getcard();cout<<"??×¥μ?á?ç??? ";t.card[t.count]->GetText();cout<<endl;t.count++;return 1;}elsereturn 0;}}}int Player::showpoint(){int j=0,sum=0;while(card[j]!=NULL){if(card[j]->outnum()>10||card[j]->outnum()==0) sum+=1;else sum+=card[j]->outnum();j++;}return sum;}void Player::showpoker(){int j=0;while(card[j]!=NULL){card[j]->GetText();j++;}cout<<endl;}void Player::reset(){for(int i=0;i<20;i++)card[i]=NULL;count=0;}char *Newgame::victory(){int k=1;Player *r=player[0];while(k<num){if(r->showpoint()==player[k]->showpoint()){if(!strcmp(player[k]->name,boss)){ r=player[k]; k++;continue;}else{ k++;continue;}}if(r->showpoint()<=21&&player[k]->showpoint()<=21) { if(r->showpoint()<player[k]->showpoint())r=player[k];}else{if(r->showpoint()<=21) r=r;else r=player[k];}k++;}r->score++;return r->name;}void Newgame::begin(){cout<<"???ë?????aä?è???!"<<endl;poker->Xipai();int w=0;bool end=true;while(1){strcpy(boss,player[w]->name);cout<<"???ëä?"<<player[w]->name<<"×é×ˉ!"<<endl;while(1){for(int l=w;l<w+num;l++){if(callpoker(*player[l%num]))end=false;}if(end)break;else end=true;}cout<<"è??çä?£o"<<victory()<<endl;cout<<"?é×?μ?μ?äy?°???a£o"<<endl;for(int k=0;k<num;k++){cout<<player[k]->name<<": "<<player[k]->showpoint()<<" ";player[k]->showpoker();}for(int u=0;u<num;u++){cout<<player[u]->name<<"μ??y???a£o"<<player[u]->score<<endl; player[u]->reset();}cout<<"ä????åD?è???(Y or N)?"<<endl;char h;cin>>h;while(h!='y'&&h!='Y'&&h!='n'&&h!='N'){cout<<"??â?â?ä?â?ä????yâ?£o£¨Y or N)?"<<endl;cin>>h;}if(h=='Y'||h=='y'){w=(w+1)%num;end=true;poker->Xipai();system("cls");}else{cout<<"D?D?ä1è?£?"<<endl;break;}}}void main(){srand((unsigned)time(NULL)); Newgame game;game.begin();}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
package trys;public class Card {/*** <p>目标:获取和设置牌得类型和面值* <p>@param type,value* <p>@author Lee*/private int value=0; //代表纸牌的面值private int type=0; //代表纸牌的花色public Card(int type,int value){ //构造方法,给面值和花色赋值this.value=value;this.type=type;}//定义方法获取类型public int getType(){return type;}//定义方法获取面值public int getValue(){return value;}//定义方法设置纸牌的类型public void setType(int type){ this.type=type;}//定义方法设置纸牌的面值public void setValue(int value){ this.value=value;}}package trys;import java.awt.Container;import javax.swing.ImageIcon;import javax.swing.JLabel;public class CardManager {/*** <p>目的:初始化牌,生成,和发牌* <p>@version Lee*/public Card[] cards=new Card[52]; //定义数组存放纸牌/*初始化纸牌*/public void initCards(){for(int i=1;i<=4;i++){ //纸牌类型for(int j=1;j<=13;j++){ //纸牌面值cards[(i-1)*13+j-1]=new Card(i,j);}}}/*随机生成牌号*/public void randomCards(){Card temp=null; //从新定义纸牌的类型for(int i=0;i<52;i++){int a=(int)(Math.random()*52);int b=(int)(Math.random()*52);temp=cards[a];cards[a]=cards[b];cards[b]=temp;}}/*定义方法,发牌*/public void gameStart(JLabel game[],Container c){ //在容器中删除标签组件if(game[0]!=null){for(int i=0;i<52;i++){c.remove(game[i]);}c.repaint();}/*在容器中放置52个组件,用于盛放图片*/for(int i=0;i<52;i++){game[i]=new JLabel();game[i].setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));}//设置标签组件的图片为rear.gif,即牌得背面for(int i=0;i<52;i++){game[i].setIcon(newImageIcon("images/aabb.jpg"));}}}package trys;import java.awt.Dimension;import java.awt.Rectangle;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Vector;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;public class GameFrame extends JFrame implements ActionListener{JButton clear_btn=new JButton(); //洗牌按钮JButton compute_btn=new JButton(); //游戏开始按钮JButton game_btn=new JButton();//玩家按钮JButton gameover_btn=new JButton(); //游戏结束按钮JLabel game[]=new JLabel[52]; //放置52张牌得标签框CardManager cm=new CardManager(); //定义指派管理类的对象int i=0; //记录抓牌数int computer_dot=0; //记录电脑点数int game_dot=0; //记录玩家点数Vector v=new Vector(); //存储电脑抓的纸牌JLabel jLabel1=new JLabel();JLabel jLabel2=new JLabel();public GameFrame(){getContentPane().setLayout(null);this.setTitle("二十一点游戏");this.setSize(800,500);//获得当前屏幕的宽和高DimensionscreenSize=Toolkit.getDefaultToolkit().getScreenSiz e();Dimension frameSize=this.getSize(); //获得当前窗体的宽和高//设置窗体剧中if(frameSize.height>screenSize.height) frameSize.height=screenSize.height;if(frameSize.width>screenSize.width) frameSize.width=screenSize.width;this.setLocation((screenSize.width-frameSize.wid th)/2,(screenSize.height-frameSize.height)/2);clear_btn.setBounds(newRectangle(78,388,86,31)); //设置位置clear_btn.setText("洗牌"); //设置标签内容clear_btn.addActionListener(this); //注册监听器compute_btn.setBounds(newRectangle(233,388,86,31));compute_btn.setEnabled(false);//不能更改compute_btn.setText("开始游戏");compute_btn.addActionListener(this);game_btn.setBounds(newRectangle(413,389,91,32));game_btn.setEnabled(false);game_btn.setText("玩家抓牌");game_btn.addActionListener(this);gameover_btn.setBounds(newRectangle(625,390,91,32));gameover_btn.setEnabled(false);gameover_btn.setText("本轮结果");gameover_btn.addActionListener(this);JMenuBar mb=new JMenuBar(); //定义菜单条JMenu mnuFile=new JMenu("文件"); //定义菜单JMenu mnuHelp=new JMenu("帮助");JMenuItem mnuFileExit=new JMenuItem("退出"); //定义菜单项JMenuItem mnuHelpAbout=new JMenuItem("关于...");this.setJMenuBar(mb); //把菜单条添加到窗体上jLabel1.setText("电脑显示牌区");jLabel1.setBounds(newRectangle(104,330,95,38));jLabel2.setText("用户显示牌区");jLabel2.setBounds(newRectangle(499,343,92,33));mb.add(mnuFile); //将菜单加到菜单条中mb.add(mnuHelp);mnuFile.add(mnuFileExit); //将菜单项添加到菜单中mnuHelp.add(mnuHelpAbout);//对菜单产生的事件进行注册mnuFileExit.addActionListener(newActionListener(){public void actionPerformed(ActionEvent e){ System.exit(0);}});mnuHelpAbout.addActionListener(newActionListener(){public void actionPerformed(ActionEvent e){ new AboutFrame();}});this.getContentPane().add(jLabel2);this.getContentPane().add(jLabel1);this.getContentPane().add(game_btn);this.getContentPane().add(clear_btn);this.getContentPane().add(gameover_btn);this.getContentPane().add(compute_btn);this.setVisible(true);}public static void main(String [] args){GameFrame gameframe=new GameFrame();}public void actionPerformed(ActionEvent e){ //洗牌按钮if(e.getSource()==clear_btn){//关闭和开启相应的按钮compute_btn.setEnabled(true);clear_btn.setEnabled(false);//对记牌器,电脑点数和玩家点数进行初始化i=0; computer_dot=0; game_dot=0;//把标签控件数组放入窗体的窗格中cm.gameStart(game, this.getContentPane());cm.initCards(); //初始化一副纸牌cm.randomCards(); //随机打乱}//开始游戏按钮if(e.getSource()==compute_btn){//关闭和开启相应的按钮compute_btn.setEnabled(false);game_btn.setEnabled(true);//电脑抓牌for(int k=0;k<20;k++){game[i].setIcon(newImageIcon("images/aabb.jpg"));game[i].setBounds(newRectangle(50+i*20,200,71,96));getContentPane().setComponentZOrder(game[i],1);if(cm.cards[i].getValue()>10){computer_dot=computer_dot+1;}else{computer_dot=computer_dot+cm.cards[i].getValue() ;}v.add(cm.cards[i]);getContentPane().repaint();i=i+1;//如果面值大于15则停止抓牌if(computer_dot>15) return;}}//玩家抓牌按钮if(e.getSource()==game_btn){//提示玩家if(game_dot>=10){int a=JOptionPane.showConfirmDialog(null,"现在点数为:"+game_dot+"是否在抓牌","提示",JOptionPane.NO_OPTION);if(a==JOptionPane.NO_OPTION){game_btn.setEnabled(false);gameover_btn.setEnabled(true);return;}}//设置标签,显示抓到的纸牌game[i].setIcon(newImageIcon("images/"+cm.cards[i].getType()+"-"+cm.ca rds[i].getValue()+".jpg"));game[i].setBounds(newRectangle(350+i*20,200,71,96));this.getContentPane().setComponentZOrder(game[i],1);//计算扎到纸牌的面值if(cm.cards[i].getValue()<=10)game_dot=game_dot+cm.cards[i].getValue();else game_dot=game_dot+1;i=i+1; //记录抓到的牌数//面值大于21时停止抓牌,关闭和开启相应的按钮if(game_dot>21){game_btn.setEnabled(false);gameover_btn.setEnabled(true);return;}}//本轮游戏结束按钮if(e.getSource()==gameover_btn){//吧电脑的纸牌反过来for(int i=0;i<v.size();i++){Card card=(Card)v.get(i);game[i].setIcon(newImageIcon("images/"+card.getType()+"-"+card.getValu e()+".jpg"));game[i].setBounds(newRectangle(50+i*20,200,71,96));this.getContentPane().setComponentZOrder(game[i], 1);}//计算胜负String game_over="";if(game_dot>21 && computer_dot<=21)game_over="电脑获胜";else if(game_dot<=21 && computer_dot>=21) game_over="玩家获胜";else if(game_dot>=21 && computer_dot>=21) game_over="平局";else if(game_dot>computer_dot) game_over="玩家获胜";else if(game_dot<computer_dot) game_over="电脑获胜";else if(game_dot==computer_dot)game_over="平局";//以对话框的方式显示胜负String message="游戏结果\n";message=message+"电脑点数:"+String.valueOf(computer_dot)+"\n";message=message+"玩家点数:"+String.valueOf(game_dot)+"\n";message=message+"游戏结果:"+game_over;JOptionPane.showMessageDialog(null,message,"本轮游戏的结果",RMATION_MESSAGE);//设置按钮可操作clear_btn.setEnabled(true);compute_btn.setEnabled(true);game_btn.setEnabled(true);gameover_btn.setEnabled(true);}}}package trys;import java.awt.Dimension;import java.awt.Rectangle;import java.awt.Toolkit;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JTextArea;public class AboutFrame extends JFrame{JLabel jLabel1=new JLabel();JTextArea ta1=new JTextArea();JLabel jLabel2=new JLabel();JTextArea ta2=new JTextArea();public AboutFrame(){getContentPane().setLayout(null);jLabel1.setText("游戏规则");jLabel1.setBounds(new Rectangle(27,0,97,36));jLabel2.setText("声明");jLabel2.setBounds(new Rectangle(26,176,80,27));ta2.setEditable(false);ta2.setLineWrap(true);ta2.setBounds(new Rectangle(26,207,398,63));ta1.setColumns(40);ta1.setLineWrap(true);this.setTitle("关于");this.getContentPane().add(jLabel1);this.getContentPane().add(ta1);this.getContentPane().add(jLabel2);this.getContentPane().add(ta2);this.setEnabled(false);ta1.setText("电脑先抓牌,玩家后抓牌.计算自己的面值总额,比较面值数,如果面值总数都大于21点,则平局.如果玩家和电脑的面值总数有一个大于21点,另一个" +"不大于21点,则不大于21点的为赢家.如果都不大于21点,则点数多达额赢");ta1.setBounds(new Rectangle(25,36,392,130));ta2.setText("游戏中的,纸牌的图片来自windowXp的纸牌游戏,图片版权属于Java_Lee 所有");this.setSize(450,300);Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();//获得当前窗体的宽和高Dimension frameSize=this.getSize();//设置窗体剧中if(frameSize.height>screenSize.height)frameSize.height=screenSize.height;if(frameSize.width>screenSize.width)frameSize.width=screenSize.width;this.setLocation((screenSize.width-frameSize.width)/2,(screenSize.height-frameSize.height)/2);this.setVisible(true);}}。