導航:首頁 > 源碼編譯 > canvas游戲源碼

canvas游戲源碼

發布時間:2023-03-24 02:45:08

① cocos creator見縫插針源碼游戲結束的代碼邏輯

別玩游戲

② 求一段java編寫的貪吃蛇小程序源代碼

用MVC方式實現的貪吃蛇游戲,共有4個類。運行GreedSnake運行即可。主要是觀察者模式的使用,我已經添加了很多注釋了。
1、
/*
* 程序名稱:貪食蛇
* 原作者:BigF
* 修改者:algo
* 說明:我以前也用C寫過這個程序,現在看到BigF用Java寫的這個,發現雖然作者自稱是Java的初學者,
* 但是明顯編寫程序的素養不錯,程序結構寫得很清晰,有些細微得地方也寫得很簡潔,一時興起之
* 下,我認真解讀了這個程序,發現數據和表現分開得很好,而我近日正在學習MVC設計模式,
* 因此嘗試把程序得結構改了一下,用MVC模式來實現,對源程序得改動不多。
* 我同時也為程序增加了一些自己理解得注釋,希望對大家閱讀有幫助。
*/

package mvcTest;

/**
* @author WangYu
* @version 1.0
* Description:
* </pre>
* Create on :Date :2005-6-13 Time:15:57:16
* LastModified:
* History:
*/
public class GreedSnake {
public static void main(String[] args) {
SnakeModel model = new SnakeModel(20,30);
SnakeControl control = new SnakeControl(model);
SnakeView view = new SnakeView(model,control);
//添加一個觀察者,讓view成為model的觀察者
model.addObserver(view);

(new Thread(model)).start();
}
}

-------------------------------------------------------------
2、

package mvcTest;

//SnakeControl.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
* MVC中的Controler,負責接收用戶的操作,並把用戶操作通知Model
*/
public class SnakeControl implements KeyListener{
SnakeModel model;

public SnakeControl(SnakeModel model){
this.model = model;
}

public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (model.running){ // 運行狀態下,處理的按鍵
switch (keyCode) {
case KeyEvent.VK_UP:
model.changeDirection(SnakeModel.UP);
break;
case KeyEvent.VK_DOWN:
model.changeDirection(SnakeModel.DOWN);
break;
case KeyEvent.VK_LEFT:
model.changeDirection(SnakeModel.LEFT);
break;
case KeyEvent.VK_RIGHT:
model.changeDirection(SnakeModel.RIGHT);
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_PAGE_UP:
model.speedUp();
break;
case KeyEvent.VK_SUBTRACT:
case KeyEvent.VK_PAGE_DOWN:
model.speedDown();
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
model.changePauseState();
break;
default:
}
}

// 任何情況下處理的按鍵,按鍵導致重新啟動游戲
if (keyCode == KeyEvent.VK_R ||
keyCode == KeyEvent.VK_S ||
keyCode == KeyEvent.VK_ENTER) {
model.reset();
}
}

public void keyReleased(KeyEvent e) {
}

public void keyTyped(KeyEvent e) {
}
}
-------------------------------------------------------------
3、
/*
*
*/

package mvcTest;

/**
* 游戲的Model類,負責所有游戲相關數據及運行
* @author WangYu
* @version 1.0
* Description:
* </pre>
* Create on :Date :2005-6-13 Time:15:58:33
* LastModified:
* History:
*/
//SnakeModel.java
import javax.swing.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Random;

/**
* 游戲的Model類,負責所有游戲相關數據及運行
*/
class SnakeModel extends Observable implements Runnable {
boolean[][] matrix; // 指示位置上有沒蛇體或食物
LinkedList nodeArray = new LinkedList(); // 蛇體
Node food;
int maxX;
int maxY;
int direction = 2; // 蛇運行的方向
boolean running = false; // 運行狀態

int timeInterval = 200; // 時間間隔,毫秒
double speedChangeRate = 0.75; // 每次得速度變化率
boolean paused = false; // 暫停標志

int score = 0; // 得分
int countMove = 0; // 吃到食物前移動的次數

// UP and DOWN should be even
// RIGHT and LEFT should be odd
public static final int UP = 2;
public static final int DOWN = 4;
public static final int LEFT = 1;
public static final int RIGHT = 3;

public SnakeModel( int maxX, int maxY) {
this.maxX = maxX;
this.maxY = maxY;

reset();
}

public void reset(){
direction = SnakeModel.UP; // 蛇運行的方向
timeInterval = 200; // 時間間隔,毫秒
paused = false; // 暫停標志
score = 0; // 得分
countMove = 0; // 吃到食物前移動的次數

// initial matirx, 全部清0
matrix = new boolean[maxX][];
for (int i = 0; i < maxX; ++i) {
matrix[i] = new boolean[maxY];
Arrays.fill(matrix[i], false);
}

// initial the snake
// 初始化蛇體,如果橫向位置超過20個,長度為10,否則為橫向位置的一半
int initArrayLength = maxX > 20 ? 10 : maxX / 2;
nodeArray.clear();
for (int i = 0; i < initArrayLength; ++i) {
int x = maxX / 2 + i;//maxX被初始化為20
int y = maxY / 2; //maxY被初始化為30
//nodeArray[x,y]: [10,15]-[11,15]-[12,15]~~[20,15]
//默認的運行方向向上,所以游戲一開始nodeArray就變為:
// [10,14]-[10,15]-[11,15]-[12,15]~~[19,15]
nodeArray.addLast(new Node(x, y));
matrix[x][y] = true;
}

// 創建食物
food = createFood();
matrix[food.x][food.y] = true;
}

public void changeDirection(int newDirection) {
// 改變的方向不能與原來方向同向或反向
if (direction % 2 != newDirection % 2) {
direction = newDirection;
}
}

/**
* 運行一次
* @return
*/
public boolean moveOn() {
Node n = (Node) nodeArray.getFirst();
int x = n.x;
int y = n.y;

// 根據方向增減坐標值
switch (direction) {
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}

// 如果新坐標落在有效范圍內,則進行處理
if ((0 <= x && x < maxX) && (0 <= y && y < maxY)) {

if (matrix[x][y]) { // 如果新坐標的點上有東西(蛇體或者食物)
if (x == food.x && y == food.y) { // 吃到食物,成功
nodeArray.addFirst(food); // 從蛇頭贈長

// 分數規則,與移動改變方向的次數和速度兩個元素有關
int scoreGet = (10000 - 200 * countMove) / timeInterval;
score += scoreGet > 0 ? scoreGet : 10;
countMove = 0;

food = createFood(); // 創建新的食物
matrix[food.x][food.y] = true; // 設置食物所在位置
return true;
} else // 吃到蛇體自身,失敗
return false;

} else { // 如果新坐標的點上沒有東西(蛇體),移動蛇體
nodeArray.addFirst(new Node(x, y));
matrix[x][y] = true;
n = (Node) nodeArray.removeLast();
matrix[n.x][n.y] = false;
countMove++;
return true;
}
}
return false; // 觸到邊線,失敗
}

public void run() {
running = true;
while (running) {
try {
Thread.sleep(timeInterval);
} catch (Exception e) {
break;
}

if (!paused) {
if (moveOn()) {
setChanged(); // Model通知View數據已經更新
notifyObservers();
} else {
JOptionPane.showMessageDialog(null,
"you failed",
"Game Over",
JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
running = false;
}

private Node createFood() {
int x = 0;
int y = 0;
// 隨機獲取一個有效區域內的與蛇體和食物不重疊的位置
do {
Random r = new Random();
x = r.nextInt(maxX);
y = r.nextInt(maxY);
} while (matrix[x][y]);

return new Node(x, y);
}

public void speedUp() {
timeInterval *= speedChangeRate;
}

public void speedDown() {
timeInterval /= speedChangeRate;
}

public void changePauseState() {
paused = !paused;
}

public String toString() {
String result = "";
for (int i = 0; i < nodeArray.size(); ++i) {
Node n = (Node) nodeArray.get(i);
result += "[" + n.x + "," + n.y + "]";
}
return result;
}
}

class Node {
int x;
int y;

Node(int x, int y) {
this.x = x;
this.y = y;
}
}
------------------------------------------------------------
4、

package mvcTest;

//SnakeView.java
import javax.swing.*;
import java.awt.*;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;

/**
* MVC模式中得Viewer,只負責對數據的顯示,而不用理會游戲的控制邏輯
*/
public class SnakeView implements Observer {
SnakeControl control = null;
SnakeModel model = null;

JFrame mainFrame;
Canvas paintCanvas;
JLabel labelScore;

public static final int canvasWidth = 200;
public static final int canvasHeight = 300;

public static final int nodeWidth = 10;
public static final int nodeHeight = 10;

public SnakeView(SnakeModel model, SnakeControl control) {
this.model = model;
this.control = control;

mainFrame = new JFrame("GreedSnake");

Container cp = mainFrame.getContentPane();

// 創建頂部的分數顯示
labelScore = new JLabel("Score:");
cp.add(labelScore, BorderLayout.NORTH);

// 創建中間的游戲顯示區域
paintCanvas = new Canvas();
paintCanvas.setSize(canvasWidth + 1, canvasHeight + 1);
paintCanvas.addKeyListener(control);
cp.add(paintCanvas, BorderLayout.CENTER);

// 創建底下的幫助欄
JPanel panelButtom = new JPanel();
panelButtom.setLayout(new BorderLayout());
JLabel labelHelp;
labelHelp = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.NORTH);
labelHelp = new JLabel("ENTER or R or S for start;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.CENTER);
labelHelp = new JLabel("SPACE or P for pause", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.SOUTH);
cp.add(panelButtom, BorderLayout.SOUTH);

mainFrame.addKeyListener(control);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}

void repaint() {
Graphics g = paintCanvas.getGraphics();

//draw background
g.setColor(Color.WHITE);
g.fillRect(0, 0, canvasWidth, canvasHeight);

// draw the snake
g.setColor(Color.BLACK);
LinkedList na = model.nodeArray;
Iterator it = na.iterator();
while (it.hasNext()) {
Node n = (Node) it.next();
drawNode(g, n);
}

// draw the food
g.setColor(Color.RED);
Node n = model.food;
drawNode(g, n);

updateScore();
}

private void drawNode(Graphics g, Node n) {
g.fillRect(n.x * nodeWidth,
n.y * nodeHeight,
nodeWidth - 1,
nodeHeight - 1);
}

public void updateScore() {
String s = "Score: " + model.score;
labelScore.setText(s);
}

public void update(Observable o, Object arg) {
repaint();
}
}
希望採納

③ 貪吃蛇游戲的源代碼



貪吃蛇源碼:

<!doctype html>
<html>
<body style='overflow:hidden'>
<canvas id="can" width="400" height="400" style="background:Black;display: block;margin:20px auto;"></canvas>
<script>
var sn = [ 42, 41 ], dz = 43, fx = 1, n, ctx = document.getElementById("can").getContext("2d");
function draw(t, c) {
ctx.fillStyle = c;
ctx.fillRect(t % 20 * 20 + 1, ~~(t / 20) * 20 + 1, 18, 18);
}
document.onkeydown = function(e) {
fx = sn[1] - sn[0] == (n = [ -1, -20, 1, 20 ][(e || event).keyCode - 37] || fx) ? fx : n
};
!function() {
sn.unshift(n = sn[0] + fx);
if (sn.indexOf(n, 1) > 0 || n<0||n>399 || fx == 1 && n % 20 == 0 || fx == -1 && n % 20 == 19)
return alert("GAME OVER");
draw(n, "Lime");
if (n == dz) {
while (sn.indexOf(dz = ~~(Math.random() * 400)) >= 0);
draw(dz, "Yellow");
} else
draw(sn.pop(), "Black");
setTimeout(arguments.callee, 130);
}();
</script>
</body>
</html>

④ UGUI筆記——Canvas,CanvasScaler,GraphicRaycaster

我們在Unity創建一個Canvas游戲對象,會默認添加Canvas,CanvasScaler,GraphicRaycaster這三個組件,下面會詳細介紹一下各個組租源件的作用。

Canvas 組件是UI布局和渲染的抽象空間,所有的UI都必須在此元素之下(子物件),簡單來說 Canvas 就是渲染 UI 的組件。
UI渲染的方式(Render Mode)型戚,有以下三種

GraphicRaycaster會觀察 Canvas下所有圖形,並檢測是否被擊中,射線檢測其實就是指定位置與方向後,投射一條隱形線並判斷是否有碰撞體在線上,用於判斷是否點選到UI上。

舉例:如果畫面上有一個 Button 與 Cube 位置故意重疊,現在點擊重疊之處會發現 Button 還是會被觸發。

Blocked Objects 設定為 Three D,再次點選重疊區域,會發現 Cube 會阻礙射線檢測,此時按鈕不會有反應

Canvas Scaler是Unity UI系統中,控制UI元素大小和像素密度的組件,Canvas Scaler的縮放比例影響Canvas下的元素,包含字體大小和圖像邊界。

可以看出,Canvas Scaler 通過設置Canvas下的Scale Factor,縮放所有在此Canvas下的元素

Canvas Size 始終等於 Screen Size,通過Scale Factor直接縮放所有UI元素

介紹Reference Pixels Per Unit之前需要先介紹圖片設置中的Pixels Per Unit(表示一張Sprite,在世界坐標中一單位由幾個Pixel組成)

這里使用的測試圖片為原始尺寸100*100 的圖片

由此可以推導出公式: Sprite 在世界坐標中大小 = 原圖大小(Pixels) / Pixels Per Unit

讓我們回到 Reference Pixels Per Unit,官方解釋是,如果圖片有設置Pixels Per Unit,則會將Sprite 的 1 pixel 轉換成 UI 中的 1 pixel,下面將以Image源碼說明:

可以看出 Image 通過過 spritePixelsPerUnit / referencePixelsPerUnit 方式算出新的 pixelsPerUnit

在設定 Image 圖片大小時,是把 Sprite寬高卜型陵 / pixelsPerUnit

由此可以推導出公式: UI大小 = 原圖大小(Pixels) / (Pixels Per Unit / Reference Pixels Per Unit)
或者 UI大小 = Sprite 在世界坐標中大小 * Reference Pixels Per Unit

通過設定的Reference Resolution(預設屏幕大小)來縮放

分別對ScaleFactor Width、Height取對數後,再進行平均混合,那為什麽不直接使用Match對Width、Height進行混合呢???讓我們來比較一下

完整源碼演算法

通過硬體設備的Dpi(Dots Per Inch 每英吋點數),進行縮放

⑤ h5游戲源碼如何修改樣式沒有css啊

看你這個架構 應該是用canvas畫布做的, 沒辦法用css修改樣式的, 只能在js裡面找到相應的語句做修改

⑥ 請用python編一個小游戲,如五子棋,連連看,貪吃蛇,掃雷,計算器等等

#!/usr/bin/python
from Tkinter import *
import random
class snake(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.body = [(0,0)]
self.bodyid = []
self.food = [ -1, -1 ]
self.foodid = -1
self.gridcount = 10
self.size = 500
self.di = 3
self.speed = 500
self.top = self.winfo_toplevel()
self.top.resizable(False, False)
self.grid()
self.canvas = Canvas(self)
self.canvas.grid()
self.canvas.config(width=self.size, height=self.size,relief=RIDGE)
self.drawgrid()
s = self.size/self.gridcount
id = self.canvas.create_rectangle(self.body[0][0]*s,self.body[0][1]*s,
(self.body[0][0]+1)*s, (self.body[0][1]+1)*s, fill="yellow")
self.bodyid.insert(0, id)
self.bind_all("<KeyRelease>", self.keyrelease)
self.drawfood()
self.after(self.speed, self.drawsnake)
def drawgrid(self):
s = self.size/self.gridcount
for i in range(0, self.gridcount+1):
self.canvas.create_line(i*s, 0, i*s, self.size)
self.canvas.create_line(0, i*s, self.size, i*s)
def drawsnake(self):
s = self.size/self.gridcount
head = self.body[0]
new = [head[0], head[1]]
if self.di == 1:
new[1] = (head[1]-1) % self.gridcount
elif self.di == 2:
new[0] = (head[0]+1) % self.gridcount
elif self.di == 3:
new[1] = (head[1]+1) % self.gridcount
else:
new[0] = (head[0]-1) % self.gridcount
next = ( new[0], new[1] )
if next in self.body:
exit()
elif next == (self.food[0], self.food[1]):
self.body.insert(0, next)
self.bodyid.insert(0, self.foodid)
self.drawfood()
else:
tail = self.body.pop()
id = self.bodyid.pop()
self.canvas.move(id, (next[0]-tail[0])*s, (next[1]-tail[1])*s)
self.body.insert(0, next)
self.bodyid.insert(0, id)
self.after(self.speed, self.drawsnake)
def drawfood(self):
s = self.size/self.gridcount
x = random.randrange(0, self.gridcount)
y = random.randrange(0, self.gridcount)
while (x, y) in self.body:
x = random.randrange(0, self.gridcount)
y = random.randrange(0, self.gridcount)
id = self.canvas.create_rectangle(x*s,y*s, (x+1)*s, (y+1)*s, fill="yellow")
self.food[0] = x
self.food[1] = y
self.foodid = id
def keyrelease(self, event):
if event.keysym == "Up" and self.di != 3:
self.di = 1
elif event.keysym == "Right" and self.di !=4:
self.di = 2
elif event.keysym == "Down" and self.di != 1:
self.di = 3
elif event.keysym == "Left" and self.di != 2:
self.di = 4
app = snake()
app.master.title("Greedy Snake")
app.mainloop()

貪食蛇

⑦ HTML5圍住神經貓

源碼簡介 相關最新源碼
HTML5圍住神經貓游戲網頁版是一款基於HTML5 canvas、egret_loader.js和jquery.min.js等技術製作的圍住神經貓網頁版游戲源碼。
游戲玩法:

游戲隨機出現灰色圓點和橙色圓點,屏幕中央為一隻扭動的神經貓。游戲要求通過觸擊灰色圓點從而變成橙色,使橙色圓點將神經貓四周全部包圍起來,進而使其不能再行移動即為勝利。

⑧ 求一個安卓開發小游戲源代碼,臨時交作業用

package com.fiveChess;

import android.app.Activity;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;

public class MainActivity extends Activity {
GameView gameView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
Display display = this.getWindowManager().getDefaultDisplay();
gameView = new GameView(this,display.getWidth(),display.getHeight());
setContentView(gameView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("重新開始").setIcon(android.R.drawable.ic_menu_myplaces);
menu.add("退出");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getTitle().equals("重新開始")){
gameView.canPlay = true;
gameView.chess = new int[gameView.row][gameView.col];
gameView.invalidate();
}else if(item.getTitle().equals("退出")){
finish();
}
return super.onOptionsItemSelected(item);
}
}

package com.fiveChess;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.view.MotionEvent;
import android.view.View;

public class GameView extends View {
Context context = null;
int screenWidth,screenHeight;
String message = "";//提示輪到哪個玩家
int row,col; //劃線的行數和列數
int stepLength = 30;//棋盤每格間距
int[][] chess = null;//0代表沒有棋子,1代表是黑棋,2代表白旗
boolean isBlack = true;
boolean canPlay = true;
public GameView(Context context,int screenWidth,int screenHeight) {
super(context);
this.context = context;
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
this.message = "黑棋先行";
row = (screenHeight-50)/stepLength+1;
col = (screenWidth-10)/stepLength+1;
chess = new int[row][col];

}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
canvas.drawRect(0, 0, screenWidth, screenHeight, paint);//畫背景
paint.setColor(Color.BLUE);
paint.setTextSize(25);
canvas.drawText(message, (screenWidth-100)/2, 30, paint);//畫最頂層的字
paint.setColor(Color.BLACK);
//畫棋盤
for(int i=0;i<row;i++){
canvas.drawLine(10, 50+i*stepLength, 10+(col-1)*stepLength, 50+i*stepLength, paint);
}
for(int i=0;i<col;i++){
canvas.drawLine(10+i*stepLength,50,10+i*stepLength,50+(row-1)*stepLength, paint);
}

for(int r=0;r<row;r++){
for(int c=0;c<col;c++){
if(chess[r][c] == 1){
paint.setColor(Color.BLACK);
paint.setStyle(Style.FILL);
canvas.drawCircle(10+c*stepLength, 50+r*stepLength, 10, paint);
}else if(chess[r][c] == 2){
//畫白棋
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawCircle(10+c*stepLength, 50+r*stepLength, 10, paint);

paint.setColor(Color.BLACK);
paint.setStyle(Style.STROKE);
canvas.drawCircle(10+c*stepLength, 50+r*stepLength, 10, paint);
}
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(!canPlay){return false;}
float x = event.getX();
float y = event.getY();
int r = Math.round((y-50)/stepLength);
int c = Math.round((x-10)/stepLength);
if(r<0 || r>row-1 || c<0 || c>col-1){return false;}
if(chess[r][c]!=0){return false;}//若有棋子則不再畫棋子了
if(isBlack){
chess[r][c] = 1;
isBlack = false;
message = "輪到白棋";
}else{
chess[r][c] = 2;
isBlack = true;
message = "輪到黑棋";
}
invalidate();
if(judge(r, c,0,1)) return false;
if(judge(r, c,1,0)) return false ;
if(judge(r, c,1,1)) return false;
if(judge(r, c,1,-1)) return false;

return super.onTouchEvent(event);
}
private boolean judge(int r, int c,int x,int y) {//r,c表示行和列,x表示在y方向上的偏移,y表示在x方向上的偏移
int count = 1;
int a = r;
int b = c;
while(r>=0 && r<row && c>=0 && c<col && r+x>=0 && r+x<row && c+y>=0 && c+y<col && chess[r][c] == chess[r+x][c+y]){
count++;
if(y>0){
c++;
}else if(y<0){
c--;
}
if(x>0){
r++;
}else if(x<0){
r--;
}
}
while(a>=0 && a<row && b>=0 && b<col && a-x>=0 && a-x<row && b-y>=0 && b-y<col && chess[a][b] == chess[a-x][b-y]){
count++;
if(y>0){
b--;
}else if(y<0){
b++;
}
if(x>0){
a--;
}else if(x<0){
a++;
}
}
if(count>=5){
String str = "";
if(isBlack){
str = "白棋勝利";
}else{
str = "黑棋勝利";
}
new AlertDialog.Builder(context).setTitle("游戲結束").setMessage(str).setPositiveButton("重新開始", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
chess = new int[row][col];
invalidate();

}
}).setNegativeButton("觀看棋局", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
canPlay = false;

}
}).show();
return true;
}

return false;
}
}
PS:五子棋,無需圖片,直接在程序里畫出來的。注意我發的是兩個文件,一個activity,一個類文件,別把它當成一個文件了

⑨ 用java設計一個球從屏幕頂上降落到屏幕下面 很急!!!快的我加分

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class MainTest {
public static void main(String[] args) {
MainTest thisClass = new MainTest();
}

private static final int SIZEX = 640;
private static final int SIZEY = 480;
private static final int SIZER = 20;
private static final int DELAY = 30;
private static final int STEP = 1;
private static final String START_TXT = "Start";
private static final String STOP_TXT = "Stop";
private static final String PAUSE_TXT = "Pause";
private static final String Resume_TXT = "Resume";

private BufferedImage bm2;
private JButton btn1;
private JButton btn2;
private PaintPanel paintPanel;
private Timer timer;
private double px;
private double py;
private double sx;
private double sy;

private MainTest() {
px = 1 + Math.random() * (SIZEX - 2 * SIZER - 2);
py = 1 + Math.random() * (SIZEY - 2 * SIZER - 2);
bm2 = new BufferedImage(SIZER * 2, SIZER * 2, BufferedImage.TYPE_4BYTE_ABGR);
timer = new Timer(DELAY, new MyActionListener(1));
initBm2(bm2);
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
JPanel topPanel = new JPanel(new FlowLayout());
mainFrame.add(topPanel, BorderLayout.NORTH);
btn1 = new JButton(START_TXT);
btn1.addActionListener(new MyActionListener(2));
topPanel.add(btn1);
btn2 = new JButton(PAUSE_TXT);
topPanel.add(btn2);
paintPanel = new PaintPanel();
mainFrame.add(paintPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}

private void initBm2(BufferedImage bm2) {
Graphics2D g2 = bm2.createGraphics();
int step = 255 / SIZER;
for (int i = 0; i < SIZER; i++) {
g2.setColor(new Color((255 - i * step) / 2, (i * step) / 2 + 127, 255 - i * step));
g2.fillArc(i, i, (SIZER - i) * 2, (SIZER - i) * 2, 0, 360);
}
}

private class MyActionListener implements ActionListener {
private int type;

private MyActionListener(int type) {
this.type = type;
}

public void actionPerformed(ActionEvent e) {
if (this.type == 1) {
px += sx;
py += sy;
if (px < 1 && sx < 0) {
sx = -sx;
} else if (px > SIZEX - 2 * SIZER - 2 && sx > 0) {
sx = -sx;
}
if (py < 1 && sy < 0) {
sy = -sy;
} else if (py > SIZEY - 2 * SIZER - 2 && sy > 0) {
sy = -sy;
}
paintPanel.repaint();
} else if (this.type == 2) {
if (timer.isRunning()) {
timer.stop();
btn1.setText(START_TXT);
} else {
double de = Math.PI * 2 * Math.random();
sx = Math.cos(de) * STEP;
sy = Math.sin(de) * STEP;
timer.start();
btn1.setText(STOP_TXT);
}
}
}
}

private class PaintPanel extends Component {
private static final long serialVersionUID = 1L;

public Dimension getPreferredSize() {
return new Dimension(SIZEX, SIZEY);
}

public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, SIZEX, SIZEY);
g.drawImage(bm2, (int) px, (int) py, SIZER * 2, SIZER * 2, null);
g.dispose();
}
}
}

⑩ Python程序開發之簡單小程序實例(11)小游戲-跳動的小球

Python程序開發之簡單小程序實例

(11)小 游戲 -跳動的小球

一、項目功能

用戶控制擋板來阻擋跳動的小球。

二、項目分析

根據項目功能自定義兩個類,一個用於控制小球在窗體中的運動,一個用於接收用戶按下左右鍵時,擋板在窗體中的運動。在控制小球的類中,我們還需要考慮當小球下降時,碰到擋板時的位置判斷。

三、程序源代碼

源碼部分截圖:

源碼:

#!/usr/bin/python3.6

# -*- coding: GBK -*-

#導入相應模塊

from tkinter import *

import random

import time

#自定義小球的類 Ball

class Ball:

# 初始化

def __init__(self,canvas,paddle,color):

#傳遞畫布值

self.canvas=canvas

#傳遞擋板值

self.paddle=paddle

#畫圓並且保存其ID

self.id=canvas.create_oval(10,10,25,25,fill=color)

self.canvas.move(self.id,245,100)

#小球的水平位置起始列表

start=[-3,-2,-1,1,2,3]

#隨機化位置列表

random.shuffle(start)

self.x=start[0]

self.y=-2

self.canvas_heigh=self.canvas.winfo_height()#獲取窗口高度並保存

self.canvas_width=self.canvas.winfo_width()

#根據參數值繪制小球

def draw(self):

self.canvas.move(self.id,self.x,self.y)

pos=self.canvas.coords(self.id)#返回相應ID代表的圖形的當前坐標(左上角和右上角坐標)

#使得小球不會超出窗口

pad=self.canvas.coords(self.paddle.id)#獲取小球擋板的坐標

if pos[1]=self.canvas_heigh or(pos[3]>=pad[1] and pos[2]>=pad[0] and pos[2]

閱讀全文

與canvas游戲源碼相關的資料

熱點內容
羅蘭電影全集鬼片 瀏覽:570
免費看片的網站 瀏覽:832
逃跑鎖鏈掙扎佔有 瀏覽:728
SAF模式新建文件夾 瀏覽:815
電腦qq音樂保存在哪個文件夾 瀏覽:439
林飛是哪個小說的主角 瀏覽:248
龍泉驛區哪個電影院有情侶包廂 瀏覽:185
pdf文本框文字 瀏覽:907
武俠改編版綠帽全集 瀏覽:770
黛妃全部作品集百度網盤 瀏覽:951
阿里雲盤 周星馳電國語 瀏覽:596
艾梅伯出演的大尺度畫面 瀏覽:847
程序員贏獎視頻 瀏覽:673
領悟法則的小說 瀏覽:188
泰國女同電視劇 瀏覽:379
鏈條動力的演算法 瀏覽:1002
蝕骨危情沈修瑾結局 瀏覽:421
過年好結局是什麼 瀏覽:425
鑿空者雪域天馬人物名 瀏覽:212
手機app怎麼登陸對公賬戶 瀏覽:51